﻿@model CallCenter.Data.Models.CompanyGridViewModel

@{
    ViewBag.Title = "CompanyHistory";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<div class="row">
    <div class="divCenter">
        <input type="button" value="AddContact" onclick="@("window.location.href='" + @Url.Action("ContactHistory", "AddContact") + "'")    ;" />
        <input type="button" value="AddProduct" onclick="@("window.location.href='" + @Url.Action("ProductHistory", "AddProduct") + "'")    ;" />
    </div>
</div>

<div class="container container-table">
    <div class="row vertical-center-row">
        <div class="text-center col-md-4-col-offset-4">
                <div class="demo-section k-content">
                    <h4>Look Up Company</h4>
                    <input id="company" style="width: 50%;" />
                    <p class="demo-hint">
                        Start typing to find a company. E.g. "None"
                    </p>
                </div>
        </div>
    </div>
</div>

<button id="dirty" class="k-button">Get Filtered Results</button>
<button id="all" class="k-button">All</button>
<input type="hidden" id="userLoggedIn" value="@User.Identity.Name" />
<div id="idEmployeeList"></div>
<div id="idInvoiceEmployeeList"></div>
<div id="addcompanyGrid">
</div>
<div id="CompanyContactGrid"></div>
<div id="ProductRequestGrid"></div>
<div id="companyofficegrid"></div>
<div id="CompanyHistoryGrid"></div>
<div id="MessageGrid"></div>
<div id="ServiceContractGrid"></div>
<div id="TaskGrid"></div>
<div id="SubTaskGrid"></div>
<div id="TaskHistoryGrid"></div>
<div id="SalesLeadGrid"></div>
<div id="InvoiceGrid"></div>
<div id="InvoiceItemsGrid"></div>



<style>
    .someCssColorClass {
        color: red !important;
    }
</style>


<div id="saveConfirm" class="collapse alert alert-success alert-dismissible" role="alert">
    <i class="pull-left fa fa-check-circle fa-2x"></i>
    <button type="button" class="close"><span aria-hidden="true">&times;</span></button>
    <span>Your changes have been sucessfully saved.
    </span>
</div>

<style>
    #example {
        min-height: 500px;
    }

    #undo {
        text-align: center;
        position: absolute;
        white-space: nowrap;
        padding: 1em;
        cursor: pointer;
    }

    .armchair {
        float: left;
        margin: 30px 30px 120px 30px;
        text-align: center;
    }

        .armchair img {
            display: block;
            margin-bottom: 10px;
        }

    .file-icon {
        display: inline-block;
        float: left;
        width: 48px;
        height: 48px;
        margin-left: 10px;
        margin-top: 13.5px;
    }

    .img-file {
        background-image: url(../content/web/upload/jpg.png);
    }

    .doc-file {
        background-image: url(../content/web/upload/doc.png);
    }

    .pdf-file {
        background-image: url(../content/web/upload/pdf.png);
    }

    .xls-file {
        background-image: url(../content/web/upload/xls.png);
    }

    .zip-file {
        background-image: url(../content/web/upload/zip.png);
    }

    .default-file {
        background-image: url(../content/web/upload/default.png);
    }

    #example .file-heading {
        font-family: Arial;
        font-size: 1.1em;
        display: inline-block;
        float: left;
        width: 60%;
        margin: 0 0 0 20px;
        height: 25px;
        -ms-text-overflow: ellipsis;
        -o-text-overflow: ellipsis;
        text-overflow: ellipsis;
        overflow: hidden;
        white-space: nowrap;
    }

    #example .file-name-heading {
        font-weight: bold;
        margin-top: 20px;
    }

    #example .file-size-heading {
        font-weight: normal;
        font-style: italic;
    }

    li.k-file .file-wrapper .k-upload-action {
        position: absolute;
        top: 0;
        right: 0;
    }

    li.k-file div.file-wrapper {
        position: relative;
        height: 75px;
    }
</style>

<div id="SalesLeadUpload" class="demo-section k-content">
    <input id="hdnSalesLead" type="hidden" name="SalesID" value="" />
    <input type="file" name="files" id="files" />
</div>

<div id="SalesLeadUploadSuccess">
    <div id="SalesUploadFilesGrid"></div>
</div>
<div id="MessageUploadSuccess">
    <div id="MessageUploadFilesGrid"></div>
</div>
<div id="ProjectUploadSuccess">
    <div id="ProjectUploadFilesGrid"></div>
</div>
<div id="ProjectUpload" class="demo-section k-content">
    <input id="hdnProject" type="hidden" name="ProjectId" value="" />
    <input type="file" name="projectfiles" id="projectfiles" />
</div>


<div id="MessageUpload" class="demo-section k-content">
    <input id="hdnMessage" type="hidden" name="MessageId" value="" />
    <input type="file" name="messagefiles" id="messagefiles" />
</div>

<script id="salesfileTemplate" type="text/x-kendo-template">
    <span class='k-progress'></span>
    <div class='file-wrapper'>
        <span class='file-icon #=addExtensionClass(files[0].extension)#'></span>
        <h4 class='file-heading file-name-heading'>Name: #=name#</h4>
        <h4 class='file-heading file-size-heading'>Size: #=size# bytes</h4>
        <button type='button' class='k-upload-action'></button>
    </div>
</script>
<script id="messagefileTemplate" type="text/x-kendo-template">
    <span class='k-progress'></span>
    <div class='file-wrapper'>
        <span class='file-icon #=addExtensionClass(files[0].extension)#'></span>
        <h4 class='file-heading file-name-heading'>Name: #=name#</h4>
        <h4 class='file-heading file-size-heading'>Size: #=size# bytes</h4>
        <button type='button' class='k-upload-action'></button>
    </div>
</script>
<script id="projectfileTemplate" type="text/x-kendo-template">
    <span class='k-progress'></span>
    <div class='file-wrapper'>
        <span class='file-icon #=addExtensionClass(files[0].extension)#'></span>
        <h4 class='file-heading file-name-heading'>Name: #=name#</h4>
        <h4 class='file-heading file-size-heading'>Size: #=size# bytes</h4>
        <button type='button' class='k-upload-action'></button>
    </div>
</script>
<script>
    function HideAllUplods() {
        $("#SalesLeadUpload").hide();
        $("#ProjectUpload").hide();
        $("#MessageUpload").hide();
        $("#SalesLeadUploadSuccess").hide();
        $("#MessageUploadSuccess").hide();
        $("#ProjectUploadSuccess").hide();
    }
</script>
@* ...
    Show SalesLead Upload

*@
<script>
    $(document).ready(function () {
        $("#SalesLeadUpload").hide();
        $("#ProjectUpload").hide();
        $("#MessageUpload").hide();
        $("#SalesLeadUploadSuccess").hide();
    });
    $("#files").kendoUpload({
        multiple: true,
        async: {
            saveUrl: "/Upload/Save",
            removeUrl: "/Upload/Remove",
            autoUpload: false
        },
        upload: function (e) {

            e.data = { SalesID: $("#hdnSalesLead").val() };
        },
        success: function (e) {
            console.log("FileUploadSuccess");
            console.log(e);

            $("#SalesLeadUpload").hide();
            $(".k-upload-files.k-reset").find("li").remove();
            showSalesUploadFiles($("#hdnSalesLead").val());


        },
        template: kendo.template($('#salesfileTemplate').html())
    });



    function addExtensionClass(extension) {
        switch (extension) {
            case '.jpg':
            case '.img':
            case '.png':
            case '.gif':
                return "img-file";
            case '.doc':
            case '.docx':
                return "doc-file";
            case '.xls':
            case '.xlsx':
                return "xls-file";
            case '.pdf':
                return "pdf-file";
            case '.zip':
            case '.rar':
                return "zip-file";
            default:
                return "default-file";
        }
    }

    function showSalesUploadFiles(SalesLeadId) {
        var gridInEditMode = false;
        HideAllUplods();
        $("#SalesLeadUploadSuccess").show();

        var dataSource = new kendo.data.DataSource({
            transport: {
                read: function (options) {
                    $.ajax({
                        type: "POST",
                        url: "../Upload/GetSalesUploadfiles",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify({ SalesLeadId: SalesLeadId }),

                        success: function (data) {

                            options.success(data);
                        },

                        error: function (request, status, error) {

                            alert(request.responseText);
                        }
                    });
                },

                destroy: function (options) {

                    $.ajax({
                        type: "POST",
                        url: "../Upload/DeleteUploadedFiles",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify({ SalesLeadId: SalesLeadId, id: options.data.Id }),

                        success: function (data) {

                            options.success(data);
                        }
                    });
                },
                parameterMap: function (options) {
                    return kendo.stringify(options); // kendo.stringify serializes to JSON string
                },

            },
            schema: {
                model: {
                    id: "id",
                    fields: {
                        id: {
                            editable: false, nullable: true,
                            type: "int"
                        },

                        Name:
                            {
                                type: "string"
                            },
                        URL:
                            {

                                type: "string"
                            },


                        error: function (a) {

                            $('#CompanyHistoryGrid').data("kendoGrid").cancelChanges();
                        },

                    }
                }
            }
        });


        $("#SalesUploadFilesGrid").kendoGrid({
            dataSource: dataSource,
            scrollable: true,
            height: "250px",
            pageable: true,
            height: 300,
            columns: [

          {
              field: "Name", title: "Name", filterable: false,
              template: "<a href='#=URL#' download style=cursor: pointer;'> #= Name #</a>", width: "8em"
          },

          //{ field: "URL", title: "URL", width: "8em" },


          {
              title: "&nbsp;",
              width: "25em",
              //command: ["edit", "destroy"]
              command: [
                  {
                      name: "Delete",


                      click: function (e) {
                          debugger;
                          var tr = $(e.target).closest("tr"); //get the row for deletion
                          var dataItem = this.dataItem(tr); //get the row data so it can be referred later

                          deleteTopicConfirmation(e, this);

                          return false;
                      }
                  }
              ]
          }
            ],
            filterable: {
                extra: false,
                operators: {
                    string: {
                        eq: "Is equal to",
                        neq: "Is not equal to",
                        contains: "Contains"
                    }
                }
            },

            editable: "popup",
            sortable: {
                mode: "single",
                allowUnsort: false
            },
            selectable: true,



            cancel: function () {
                gridInEditMode = false;
            }
        });
        function deleteTopicConfirmation(e, widget) {
            var grid = $('#SalesUploadFilesGrid').data("kendoGrid");
            deleteConfirmation(e, widget, grid);
        }

        function deleteConfirmation(e, widget, grid) {

            var currentRow = $(e.target).closest("tr"); //get the row for deletion

            var currentRowData = widget.dataItem(currentRow); //get the row data so it can be  referred later

            var kendoWindow = $("<div />").kendoWindow({

                title: "Confirmation",
                resizable: true,
                modal: true,
                width: "400px",
                deactivate: function () {
                    $('.k-window, .k-overlay').remove();
                }
            });

            kendoWindow.data("kendoWindow")

                .content($("#delete-confirmation").html())

                .center().open();

            kendoWindow

                .find(".delete-confirm,.delete-cancel")
                .click(function () {
                    if ($(this).hasClass("delete-confirm")) {

                        grid.dataSource.remove(currentRowData);

                        grid.dataSource.sync();

                    }

                    $(this).closest("[data-role=window]").kendoWindow("close");

                });

        }
        dataSource.bind("requestEnd", showSuccessMessage);
        function showSuccessMessage(e) {
            if (e.type === "update" || e.type === "create") {
                gridInEditMode = false;
                $("#saveConfirm").addClass('in');
                e.sender.read();
            }
        }
        $(".close").click(function () {
            $(this).parent().removeClass('in');
        });
    }







</script>
@* ...
    Show MessageUpload

*@

<script>

    $(document).ready(function () {
        $("#SalesLeadUpload").hide();
        $("#ProjectUpload").hide();
        $("#MessageUpload").hide();

        $("#MessageUploadSuccess").hide();
    });

    $("#messagefiles").kendoUpload({
        multiple: true,
        async: {

            saveUrl: "/MessageUpload/Save",
            removeUrl: "/MessageUpload/Remove",
            autoUpload: false
        },
        upload: function (e) {
            debugger;
            e.data = { MessageId: $("#hdnMessage").val() };
        },
        success: function (e) {
            console.log("FileUploadSuccess");
            console.log(e);
            //alert("Files Saved Successfully");
            $("#MessageUpload").hide();
            $(".k-upload-files.k-reset").find("li").remove();
            showMessageUploadFiles($("#hdnMessage").val());


        },
        template: kendo.template($('#messagefileTemplate').html())
    });
    function showMessageUploadFiles(MessageId) {
        var gridInEditMode = false;
        HideAllUplods();
        $("#MessageUploadSuccess").show();

        var dataSource = new kendo.data.DataSource({
            transport: {
                read: function (options) {
                    $.ajax({
                        type: "POST",
                        url: "../MessageUpload/GetMessageUploadfiles",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify({ MessageId: MessageId }),

                        success: function (data) {

                            options.success(data);
                        },

                        error: function (request, status, error) {

                            alert(request.responseText);
                        }
                    });
                },

                destroy: function (options) {

                    $.ajax({
                        type: "POST",
                        url: "../MessageUpload/DeleteUploadedFiles",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify({ MessageId: MessageId, id: options.data.Id }),

                        success: function (data) {

                            options.success(data);
                        }
                    });
                },
                parameterMap: function (options) {
                    return kendo.stringify(options); // kendo.stringify serializes to JSON string
                },

            },
            schema: {
                model: {
                    id: "id",
                    fields: {
                        id: {
                            editable: false, nullable: true,
                            type: "int"
                        },

                        Name:
                            {
                                type: "string"
                            },
                        URL:
                            {

                                type: "string"
                            },


                        error: function (a) {

                            $('#CompanyHistoryGrid').data("kendoGrid").cancelChanges();
                        },

                    }
                }
            }
        });


        $("#MessageUploadFilesGrid").kendoGrid({
            dataSource: dataSource,
            scrollable: true,
            height: "250px",
            pageable: true,
            height: 300,
            columns: [

          {
              field: "Name", title: "Name", filterable: false,
              template: "<a href='#=URL#' download style=cursor: pointer;'> #= Name #</a>", width: "8em"
          },




          {
              title: "&nbsp;",
              width: "25em",
              //command: ["edit", "destroy"]
              command: [
                  {
                      name: "Delete",


                      click: function (e) {
                          debugger;
                          var tr = $(e.target).closest("tr"); //get the row for deletion
                          var dataItem = this.dataItem(tr); //get the row data so it can be referred later

                          deleteTopicConfirmation(e, this);

                          return false;
                      }
                  }
              ]
          }
            ],
            filterable: {
                extra: false,
                operators: {
                    string: {
                        eq: "Is equal to",
                        neq: "Is not equal to",
                        contains: "Contains"
                    }
                }
            },

            editable: "popup",
            sortable: {
                mode: "single",
                allowUnsort: false
            },
            selectable: true,



            cancel: function () {
                gridInEditMode = false;
            }
        });
        function deleteTopicConfirmation(e, widget) {
            var grid = $('#MessageUploadFilesGrid').data("kendoGrid");
            deleteConfirmation(e, widget, grid);
        }

        function deleteConfirmation(e, widget, grid) {

            var currentRow = $(e.target).closest("tr"); //get the row for deletion

            var currentRowData = widget.dataItem(currentRow); //get the row data so it can be  referred later

            var kendoWindow = $("<div />").kendoWindow({

                title: "Confirmation",
                resizable: true,
                modal: true,
                width: "400px",
                deactivate: function () {
                    $('.k-window, .k-overlay').remove();
                }
            });

            kendoWindow.data("kendoWindow")

                .content($("#delete-confirmation").html())

                .center().open();

            kendoWindow

                .find(".delete-confirm,.delete-cancel")
                .click(function () {
                    if ($(this).hasClass("delete-confirm")) {

                        grid.dataSource.remove(currentRowData);

                        grid.dataSource.sync();

                    }

                    $(this).closest("[data-role=window]").kendoWindow("close");

                });

        }
        dataSource.bind("requestEnd", showSuccessMessage);
        function showSuccessMessage(e) {
            if (e.type === "update" || e.type === "create") {
                gridInEditMode = false;
                $("#saveConfirm").addClass('in');
                e.sender.read();
            }
        }
        $(".close").click(function () {
            $(this).parent().removeClass('in');
        });
    }

    function addExtensionClass(extension) {
        switch (extension) {
            case '.jpg':
            case '.img':
            case '.png':
            case '.gif':
                return "img-file";
            case '.doc':
            case '.docx':
                return "doc-file";
            case '.xls':
            case '.xlsx':
                return "xls-file";
            case '.pdf':
                return "pdf-file";
            case '.zip':
            case '.rar':
                return "zip-file";
            default:
                return "default-file";
        }
    }
</script>

@* ...
    Show Projects Uploads

*@

<script>
    $(document).ready(function () {

        $("#SalesLeadUpload").hide();
        $("#ProjectUpload").hide();
        $("#MessageUpload").hide();

        $("#ProjectUploadSuccess").hide();
    });

    $("#projectfiles").kendoUpload({
        multiple: true,
        async: {
            saveUrl: "/ProjectUpload/Save",
            removeUrl: "/ProjectUpload/Remove",
            autoUpload: false
        },
        upload: function (e) {

            e.data = { ProjectId: $("#hdnProject").val() };
        },
        success: function (e) {
            console.log("FileUploadSuccess");
            console.log(e);
            //alert("Files Saved Successfully");
            $("#ProjectUpload").hide();
            $(".k-upload-files.k-reset").find("li").remove();
            showProjectUploadFiles($("#hdnProject").val());

        },
        template: kendo.template($('#projectfileTemplate').html())
    });


    function addExtensionClass(extension) {
        switch (extension) {
            case '.jpg':
            case '.img':
            case '.png':
            case '.gif':
                return "img-file";
            case '.doc':
            case '.docx':
                return "doc-file";
            case '.xls':
            case '.xlsx':
                return "xls-file";
            case '.pdf':
                return "pdf-file";
            case '.zip':
            case '.rar':
                return "zip-file";
            default:
                return "default-file";
        }
    }



    function showProjectUploadFiles(ProjectId) {
        var gridInEditMode = false;
        HideAllUplods();
        $("#ProjectUploadSuccess").show();

        var dataSource = new kendo.data.DataSource({
            transport: {
                read: function (options) {
                    $.ajax({
                        type: "POST",
                        url: "../ProjectUpload/GetProjectUploadfiles",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify({ ProjectId: ProjectId }),

                        success: function (data) {

                            options.success(data);
                        },

                        error: function (request, status, error) {

                            alert(request.responseText);
                        }
                    });
                },

                destroy: function (options) {

                    $.ajax({
                        type: "POST",
                        url: "../ProjectUpload/DeleteUploadedFiles",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify({ ProjectId: ProjectId, id: options.data.Id }),

                        success: function (data) {

                            options.success(data);
                        }
                    });
                },
                parameterMap: function (options) {
                    return kendo.stringify(options); // kendo.stringify serializes to JSON string
                },

            },
            schema: {
                model: {
                    id: "id",
                    fields: {
                        id: {
                            editable: false, nullable: true,
                            type: "int"
                        },

                        Name:
                            {
                                type: "string"
                            },
                        URL:
                            {

                                type: "string"
                            },


                        error: function (a) {

                            $('#CompanyHistoryGrid').data("kendoGrid").cancelChanges();
                        },

                    }
                }
            }
        });


        $("#ProjectUploadFilesGrid").kendoGrid({
            dataSource: dataSource,
            scrollable: true,
            height: "250px",
            pageable: true,
            height: 300,
            columns: [

          {
              field: "Name", title: "Name", filterable: false,
              template: "<a href='#=URL#' download style=cursor: pointer;'> #= Name #</a>", width: "8em"
          },

          //{ field: "URL", title: "URL", width: "8em" },


          {
              title: "&nbsp;",
              width: "25em",
              //command: ["edit", "destroy"]
              command: [
                  {
                      name: "Delete",


                      click: function (e) {
                          debugger;
                          var tr = $(e.target).closest("tr"); //get the row for deletion
                          var dataItem = this.dataItem(tr); //get the row data so it can be referred later

                          deleteTopicConfirmation(e, this);

                          return false;
                      }
                  }
              ]
          }
            ],
            filterable: {
                extra: false,
                operators: {
                    string: {
                        eq: "Is equal to",
                        neq: "Is not equal to",
                        contains: "Contains"
                    }
                }
            },

            editable: "popup",
            sortable: {
                mode: "single",
                allowUnsort: false
            },
            selectable: true,



            cancel: function () {
                gridInEditMode = false;
            }
        });
        function deleteTopicConfirmation(e, widget) {
            var grid = $('#ProjectUploadFilesGrid').data("kendoGrid");
            deleteConfirmation(e, widget, grid);
        }

        function deleteConfirmation(e, widget, grid) {

            var currentRow = $(e.target).closest("tr"); //get the row for deletion

            var currentRowData = widget.dataItem(currentRow); //get the row data so it can be  referred later

            var kendoWindow = $("<div />").kendoWindow({

                title: "Confirmation",
                resizable: true,
                modal: true,
                width: "400px",
                deactivate: function () {
                    $('.k-window, .k-overlay').remove();
                }
            });

            kendoWindow.data("kendoWindow")

                .content($("#delete-confirmation").html())

                .center().open();

            kendoWindow

                .find(".delete-confirm,.delete-cancel")
                .click(function () {
                    if ($(this).hasClass("delete-confirm")) {

                        grid.dataSource.remove(currentRowData);

                        grid.dataSource.sync();

                    }

                    $(this).closest("[data-role=window]").kendoWindow("close");

                });

        }
        dataSource.bind("requestEnd", showSuccessMessage);
        function showSuccessMessage(e) {
            if (e.type === "update" || e.type === "create") {
                gridInEditMode = false;
                $("#saveConfirm").addClass('in');
                e.sender.read();
            }
        }
        $(".close").click(function () {
            $(this).parent().removeClass('in');
        });
    }


</script>


@* ...
    Show Company Contacts

*@
<script type="text/javascript">
    function showContacts(companyId, e) {
        HideAllUplods();
        $('#CompanyContactGrid').show();
        $('#addcompanyGrid tr.k-state-selected').removeClass('k-state-selected');
        var row = $(e).closest("tr");
        row.addClass("k-state-selected");
        $('#ProductRequestGrid').hide();
        $('#TaskGrid').hide();
        $('#SubTaskGrid').hide();
        $('#companyofficegrid').hide();

        $('#CompanyHistoryGrid').hide();
        $('#ServiceContractGrid').hide();
        $("#MessageGrid").hide();
        $('#CompanyContactGrid').empty();
        var gridInEditMode = false;
        var dataSource = new kendo.data.DataSource({
            transport: {

                read: function (options) {
                    debugger;
                    $.ajax({
                        type: "POST",
                        url: "../CompanyContacts/GetAllCompany",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        cache: false,
                        data: JSON.stringify({ id: companyId }),


                        success: function (data) {

                            options.success(data);
                        }
                    });
                },
                create: function (options) {
                    options.data.companyId = companyId;
                   

                    $.ajax({
                        type: "POST",
                        url: "../CompanyContacts/CreateCompanyContacts",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify(options.data),

                        success: function (data) {
                            if (data.Message) {
                                alert(data.Message);
                            }
                            options.success(data);
                        }
                    });
                },
                update: function (options) {
                    $.ajax({
                        type: "POST",
                        url: "../CompanyContacts/UpdateCompanyContact",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify({ id: contactId }),

                        success: function (data) {
                            if (data.Message) {
                                alert(data.Message);
                            }
                            options.success(data);
                        }
                    });
                },

                destroy: function (options) {
                    $.ajax({
                        type: "POST",
                        url: "../CompanyContacts/DeleteCompanyContact",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify({ id: options.data.id }),

                        success: function (data) {

                            options.success(data);
                        }
                    });
                },
                parameterMap: function (options) {
                    return kendo.stringify(options); // kendo.stringify serializes to JSON string
                }
            },
            pageSize: 5,
            schema: {
                model: {
                    id: "id",
                    fields: {
                        id: {
                            editable: false, nullable: true,
                            type: "int"
                        },
                        name:
                            {
                                type: "string"
                            },
                        email:
                            {
                                type: "string",
                                hidden: true,
                                editable: false,
                                nullable: true,
                            },
                        jobTitle:
                    {
                        type: "string",
                        hidden: true,
                        editable: false,
                        nullable: true,
                    },
                        department:
                   {
                       type: "string",
                       hidden: true,
                       editable: false,
                       nullable: true,
                   },
                        businessPhone:
              {
                  type: "string",
                  hidden: true,
                  editable: false,
                  nullable: true,
              },
                        cellPhone:
              {
                  type: "string",
                  hidden: true,
                  editable: false,
                  nullable: true,
              },
                        company:
             {
                 type: "string",
                 hidden: true,
                 editable: false,
                 nullable: true,
             },
                        companyId: {
                            type: "int",
                        },
                        contactId: {

                            type: "int",
                        },
                        error: function (a) {

                            $('#CompanyContactGrid').data("kendoGrid").cancelChanges();
                        },

                    }
                }
            }

        });

        function dateTimeEditor(container, options) {
            $('<input data-text-field="' + options.field + '" data-value-field="' + options.field + '" data-bind="value:' + options.field + '" data-format="' + options.format + '"/>')
            .appendTo(container)
            .kendoDateTimePicker({});
        }
        var companydataSource = new kendo.data.DataSource({
            transport: {
                read: function (options) {
                    $.ajax({
                        type: "GET",
                        url: "../CompanyContacts/GetAllContactCompany",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify({ key: "Value" }),
                        success: function (data) {
                            options.success(data);
                        }
                    });
                }
            }
        });
        $("#CompanyContactGrid").kendoGrid({
            dataSource: dataSource,
            scrollable: true,
            height: "250px",
            toolbar: [{ name: "create", text: "Add a new Contact To Company" }, "excel"], //, "save", "cancel"],
            excel: {
                allPages: true,
                fileName: "ContactsExport.xlsx"
            },
            pageable: true,

            selectable: "multiple cell",
            height: 500,
            columns: [

          { field: "name", title: "Name*", filterable: true, editor: callerAutoCompleteEditor, width: "8em" },
          { field: "email", readonly: true, title: "Email", width: "8em", },
          { field: "company", title: "company", filterable: true, width: "8em" },
          { field: "jobTitle", title: "Job Title", filterable: true, width: "8em" },
          { field: "department", title: "Department", filterable: true, width: "8em" },
            { field: "businessPhone", title: "Office Phone", filterable: true, width: "8em" },
          { field: "mobilePhone", title: "Cell Phone", width: "8em" },

          {
              title: "&nbsp;",
              width: "25em",
              command: [
                  "edit",
                  {
                      name: "Delete",
                      click: function (e) {

                          var tr = $(e.target).closest("tr"); //get the row for deletion
                          var dataItem = this.dataItem(tr); //get the row data so it can be referred later
                          //see what is coming in dataItem
                          //if (dataItem > 0) {
                          //    $("#delValidation").addClass('in')
                          //}
                          //else {

                          deleteTopicConfirmation(e, this);
                          ////}
                          return false;
                      }
                  }
              ]
          }
            ],
            filterable: {
                extra: false,
                operators: {
                    string: {
                        eq: "Is equal to",
                        neq: "Is not equal to",
                        contains: "Contains"
                    }
                }
            },

            // editable: "popup",
            editable: {
                mode: "popup"
                //template: kendo.template($("#popup-editor").html())
            },
            edit: function (e) {
                var gridInEditMode = false;
                //$(e.container).parent().css({
                //    width: '500px',
                //    height: '500px'
                //});
                e.container.find(".k-edit-label:nth-child(3)").hide();
                e.container.find(".k-edit-field:nth-child(4)").hide();
                e.container.find(".k-edit-label:nth-child(11)").hide();
                e.container.find(".k-edit-field:nth-child(12)").hide();
                e.container.find(".k-edit-label:nth-child(13)").hide();
                e.container.find(".k-edit-field:nth-child(13)").hide();
                e.container.find(".k-edit-label:nth-child(14)").hide();
                e.container.find(".k-edit-field:nth-child(14)").hide();

                e.container.find(".k-edit-label:nth-child(4)").hide();
                e.container.find(".k-edit-label:nth-child(5)").hide();
                e.container.find(".k-edit-label:nth-child(6)").hide();
                e.container.find(".k-edit-label:nth-child(7)").hide();
                e.container.find(".k-edit-label:nth-child(9)").hide();

                e.container.find(".k-edit-label:nth-child(11)").hide();

                gridInEditMode = true;
                //              e.container.find(".nested-tabstrip").kendoTabStrip({});
                //              e.container.find(".tabstrip-grid").kendoGrid({
                //                 dataSource: {

                //                      type: "odata",
                //                      transport: {
                //                          read: {
                //                              url: "/AddContact/GetAddContacts",
                //                              type: "get",
                //                              cache: false,
                //                              dataType: "json",

                //                          },
                //                          create: {
                //                              url: "/AddContact/CreateAddContact",
                //                              type: 'POST',
                //                              dataType: "json",
                //                              contentType: "application/JSON"

                //                          },
                //                          parameterMap: function (options) {
                //                              return kendo.stringify(options); // kendo.stringify serializes to JSON string
                //                          }

                //                      },

                //                      schema: {
                //                          data: function (data) {
                //                              return data;
                //                          },
                //                          total: function (data) {
                //                              return data['odata.count'];
                //                          },
                //                          model: {
                //                              id: "id",
                //                              fields: {
                //                                  id: {
                //                                      editable: false, nullable: true,
                //                                      type: "int"
                //                                  },
                //                                  name: {
                //                                      type: "string",
                //                                      hidden: true,
                //                                      editable: false
                //                                  },

                //                                  firstName: {
                //                                      type: "string",
                //                                      hidden: true,

                //                                  },
                //                                  lastName: {
                //                                      type: "string",
                //                                      hidden: true
                //                                  },
                //                                  userId:
                //                                      {
                //                                          type: "int",
                //                                          defaultValue: 0
                //                                      },

                //                                  startDate: {
                //                                      type: "date",
                //                                      editable: false
                //                                  },
                //                                  error: function (a) {
                //                                      $('#addcontactGrid').data("kendoGrid").cancelChanges();
                //                                  },
                //                              }
                //                          }
                //                      }

                //                  },
                //                  toolbar: [{ name: "create", text: "Add a Contact" }, "excel"], //, "save", "cancel"],
                //                  filterable: true,
                //                  sortable: true,
                //                  pageable: true,
                //                  height: "400px",
                //                  editable: "inline",
                //                  columns: [

                //      //{ field: "details", title: "Details", filterable: false, width: "6em",editable:false, template: "<a onclick=\"showDetails('#=id #', this);\"style=\"cursor: pointer;\"> View</a>" },
                //  { field: "name", title: "FullName", width: "10em", filterable: true },

                //   { field: "firstName", title: "First Name", width: "10em",  editable: true, filterable: false },
                //    { field: "lastName", title: "Last Name", width: "10em",  editable: true, filterable: false },

                //{
                //    field: "startDate", title: "Start Date", width: "10em", filterable: false, format: "{0:MM/dd/yyyy HH:mm tt}",
                //    editor: dateTimeEditor,
                //    filterable: {
                //        ui: "datetimepicker"
                //    }
                //},
                //  {
                //      title: "&nbsp;",
                //      width: "100em",

                //      command: [

                //          "edit",
                //          {
                //              name: "Delete",


                //              click: function (e) {

                //                  var tr = $(e.target).closest("tr"); //get the row for deletion
                //                  var dataItem = this.dataItem(tr); //get the row data so it can be referred later
                //                  //see what is coming in dataItem
                //                  //if (dataItem.QuestionAnswers.length > 0) {
                //                  //    $("#delValidation").addClass('in')
                //                  //}
                //                  //else {

                //                  deleteTopicConfirmation(e, this);
                //                  // }
                //                  return false;
                //              }
                //          }
                //      ]
                //  }
                //                  ],
                //              });

                //              debugger;
                //              dataSource.bind("requestEnd", showInnerSuccessMessage);
                //              function showInnerSuccessMessage(e) {
                //                  debugger;
                //                  alert(1);
                //                  if (e.type === "update" || e.type === "create") {
                //                     gridInEditMode = false;
                //                      $("#saveConfirm").addClass('in');
                //                      e.sender.read();
                //                  }
                //              }
                //              $(".close").click(function () {
                //                  $(this).parent().removeClass('in');
                //              });

            },

            sortable: {
                mode: "single",
                allowUnsort: false
            },
            excelExport: function (e) {
                for (var i = 0; i < e.workbook.sheets[0].columns.length; i++) {
                    e.workbook.sheets[0].columns[i].autoWidth = true;
                }
            },
            selectable: true,

            cancel: function () {
                gridInEditMode = false;
            }
        });
        dataSource.bind("requestEnd", showSuccessMessage);
        function showSuccessMessage(e) {
            if (e.type === "update" || e.type === "create") {
                gridInEditMode = false;
                $("#saveConfirm").addClass('in');
                e.sender.read();
            }
        }
        $(".close").click(function () {
            $(this).parent().removeClass('in');
        });

        function deleteTopicConfirmation(e, widget) {
            var grid = $('#CompanyContactGrid').data("kendoGrid");
            deleteConfirmation(e, widget, grid);
        }

        function deleteConfirmation(e, widget, grid) {

            var currentRow = $(e.target).closest("tr"); //get the row for deletion

            var currentRowData = widget.dataItem(currentRow); //get the row data so it can be  referred later

            var kendoWindow = $("<div />").kendoWindow({

                title: "Confirmation",
                resizable: true,
                modal: true,
                width: "400px",
                deactivate: function () {
                    $('.k-window, .k-overlay').remove();
                }
            });

            kendoWindow.data("kendoWindow")

                .content($("#delete-confirmation").html())

                .center().open();

            kendoWindow

                .find(".delete-confirm,.delete-cancel")
                .click(function () {
                    if ($(this).hasClass("delete-confirm")) {

                        grid.dataSource.remove(currentRowData);

                        grid.dataSource.sync();

                    }

                    $(this).closest("[data-role=window]").kendoWindow("close");

                });

        }

        function callerAutoCompleteEditor(container, options) {

            $('<input data-text-field="name"  data-value-field="name"  data-bind="value:' + options.field + '" style="width:245px;"/>')
                .appendTo(container)
                .kendoAutoComplete({
                    headerTemplate: '<div class="AutoCompleteHeader">' +
               '<span style="width:50%;"> Contact info</span>' +
                '<span> | </span>' +
               '<span style="width:50%;"> Company </span>' +
           '</div>',
                    template: '<span class="k-state-default" style="width:50%;">#:data.name #</span>' +
                '<span> | </span>' +
                      '<span class="k-state-default" style="width:50%;"> #:data.companyname #</span> ',
                    dataValueField: "name",
                    dataTextField: "name",
                    suggest: true,
                    placeHolder: "Enter Caller Name here",
                    filter: "contains",
                    index: 1,
                    height: 400,
                    minLength: 1,
                    dataSource: companydataSource
                });
        }
    }
</script>

@* ...
    Show Company Projects

*@

<script>
    var IsAssEmpChecked = false, assignedEmployeeIdVar = null;

    var editedUID = "";
    function showProjects(companyId, e) {
        HideAllUplods();
        var gridInEditMode = false;
        $('#addcompanyGrid tr.k-state-selected').removeClass('k-state-selected');
        var row = $(e).closest("tr");
        row.addClass("k-state-selected");
        $('#ProductRequestGrid').show();
        //$('#TaskGrid').hide();
        //$('#SubTaskGrid').hide();
        $('#CompanyContactGrid').hide();
        $('#companyofficegrid').hide();
        $('#CompanyHistoryGrid').hide();
        $('#ServiceContractGrid').hide();
        $("#MessageGrid").hide();
        $("#SalesLeadGrid").hide();
        $('#ProductRequestGrid').empty();
        var dataSource2 = new kendo.data.DataSource({
            transport: {
                read: function (options) {
                    $.ajax({
                        type: "POST",
                        url: "../ProductRequestGrid/GetCompanyProject",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        cache: false,
                        data: JSON.stringify({ id: companyId }),
                        success: function (data) {

                            options.success(data);
                        },

                        error: function (request, status, error) {
                            alert(request.responseText);
                        }
                    });
                },

                create: function (options) {
                    options.data.companyId = companyId;
                    var ProductRequestViewModel = new Object();
                    ProductRequestViewModel.id = options.data.id;

                    ProductRequestViewModel.companyId = options.data.companyId;
                    if (options.data.productId)
                        ProductRequestViewModel.productId = options.data.productId.id;

                    if (options.data.departmentId)
                        ProductRequestViewModel.departmentId = options.data.departmentId.departmentId;

                    if (options.data.projectManagerId)
                        ProductRequestViewModel.projectManagerId = options.data.projectManagerId.id;

                    if (options.data.leadProgrammerId)
                        ProductRequestViewModel.leadProgrammerId = options.data.leadProgrammerId.id;

                    if (options.data.statusId)
                        ProductRequestViewModel.statusId = options.data.statusId.status;
                    if (options.data.paidById)
                        ProductRequestViewModel.paidById = options.data.paidById.id;
                    ProductRequestViewModel.startDate = options.data.startDate;

                    ProductRequestViewModel.daysToFinish = options.data.daysToFinish;

                    ProductRequestViewModel.taskScheduleComplete = options.data.taskScheduleComplete;


                    ProductRequestViewModel.name = options.data.name;
                    ProductRequestViewModel.phone = options.data.phone;
                    ProductRequestViewModel.contractSentDate = options.data.contractSentDate;
                    ProductRequestViewModel.contractSignedDate = options.data.contractSignedDate;
                    ProductRequestViewModel.depositReceivedDate = options.data.depositReceivedDate;
                    ProductRequestViewModel.depositAmount = options.data.depositAmount;
                    ProductRequestViewModel.expectedDeliveryDate = options.data.expectedDeliveryDate;
                    ProductRequestViewModel.deliveryDate = options.data.deliveryDate;

                    ProductRequestViewModel.goLiveDate = options.data.goLiveDate;
                    ProductRequestViewModel.estimatedCost = options.data.estimatedCost;
                    ProductRequestViewModel.actualAmount = options.data.actualAmount;
                    ProductRequestViewModel.estimateDate = options.data.estimateDate;
                    ProductRequestViewModel.paidInFull = options.data.paidInFull;
                    ProductRequestViewModel.note = options.data.note;
                    ProductRequestViewModel.CommEmployeeIds = options.data.CommEmployeeIds;



                    $.ajax({
                        type: "POST",
                        url: "/ProductRequestGrid/CreateProductRequest",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify(ProductRequestViewModel),
                        success: function (data) {
                            if (data.Message) {
                                alert(data.Message);
                            }
                            options.success(data);
                        }
                    });
                },
                update: function (options) {
                    options.data.companyId = companyId;
                    $.ajax({
                        type: "POST",
                        url: "/ProductRequestGrid/UpdateProductRequest",
                        dataType: 'json',
                        data: JSON.stringify(options.data),
                        contentType: "application/JSON",
                        success: function (data) {
                            if (data.Message) {
                                alert(data.Message);
                            }
                            options.success(data);
                        }
                    });
                },

                destroy: function (options) {

                    $.ajax({
                        type: "POST",
                        url: "../ProductRequestGrid/DeleteProject",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify({ id: options.data.id }),

                        success: function (data) {

                            options.success(data);
                        }
                    });
                },
                parameterMap: function (options) {
                    return kendo.stringify(options); // kendo.stringify serializes to JSON string
                }
            },
            schema: {
                model: {
                    id: "id",
                    fields: {
                        id: {
                            editable: false, nullable: true,
                            type: "int"
                        },

                        contracts:
                            {
                                type: "int"
                            },

                        task:
                            {
                                type: "int"
                            },

                        companyId: {
                            type: "int",
                            defaultValue: companyId
                        },
                        prName: {
                            type: "string",
                            validation: { required: true }
                        },
                        product: {
                            type: "string",
                            validation: { required: true }

                        },
                        CommEmployee:
                            {
                                type: "string",

                            },
                        name: {
                            type: "string",
                            validation: { required: true }
                        },
                        statusName: {
                            type: "string",
                            validation: { required: true }

                        },
                        paidCompany:
                            {
                                type: "string",

                            },

                        daysToFinish: {
                            type: "int"

                        },
                        depositAmount: {
                            editable: true,
                            type: "int"
                        },

                        estimatedCost: {
                            type: "int",

                        },
                        actualCost: {
                            type: "int",

                        },
                        paidInFull:
                        {
                            type: "boolean",
                            defaultValue: false,
                            filterable: {
                                messages: {
                                    isTrue: "Active", // sets the text for "isTrue" radio button
                                    isFalse: "Inactive",
                                }
                            }
                        },
                        paidByName:
                            {
                                type: "string"
                            },
                        taskScheduleComplete:
                      {
                          type: "boolean",
                          defaultValue: false,
                          filterable: {
                              messages: {
                                  isTrue: "Active", // sets the text for "isTrue" radio button
                                  isFalse: "Inactive",
                              }
                          }
                      },
                        contracts:
                        {
                            editable: false,
                            nullable: true
                        },
                        description: {

                            type: "string",
                            //validation: { required: true }
                        },

                        contractSentDate: {
                            type: "date",
                            nullable: true,
                            value: "",
                            //defaultOption: null
                        },
                        contractSignedDate: {
                            type: "date",

                            nullable: true,
                            value: "",
                            //defaultOption: null
                        },

                        departmentId:
                        {
                            type: "int"
                        },

                        depositReceivedDate:
                            {
                                type: "date",

                                nullable: true,
                                value: "",
                                defaultOption: null
                            },
                        startDate: {
                            type: "date",

                            nullable: true,
                            value: "",
                            defaultOption: null
                        },
                        expectedDeliveryDate:
                            {
                                type: "date",

                                nullable: true,
                                value: "",
                                defaultOption: null
                            },
                        deliveryDate: {
                            type: "date",

                            nullable: true,
                            value: "",
                            defaultOption: null
                        },
                        note: {
                            type: "string"

                        },

                        goLiveDate: {
                            type: "date",

                            nullable: true,
                            value: "",
                            defaultOption: null
                        },
                        projectManagerName:
                            {
                                type: "string",
                                //validation: { required: true }

                            },
                        leadDeveloperName: {
                            type: "string",
                            //validation: { required: true }

                        },
                        depCode: {
                            type: "string",
                            validation: { required: true }
                        },
                        estimatedDate:
                            {
                                type: "date",
                                //  validation: { required: true },
                                nullable: true,
                                value: "",
                                defaultOption: null
                            },

                        error: function (a) {
                            $('#productRequestGrid').data("kendoGrid").cancelChanges();
                        },
                    }
                }
            }

        });
        var statusdatasource = new kendo.data.DataSource({
            transport: {
                read: function (options) {
                    $.ajax({
                        type: "GET",

                        url: "../ScratchPad/GetStatus",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify({ key: "value" }),
                        success: function (data) {
                            options.success(data);
                        }
                    });
                }
            }
        });
        var involuedEmployees = new kendo.data.DataSource({
            transport: {
                read: function (options) {
                    $.ajax({
                        type: "GET",

                        url: "../ProductRequestGrid/GetInvlouedEmployees",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        success: function (data) {
                            options.success(data);
                        }
                    });
                }
            }
        });
        var productsdataSource = new kendo.data.DataSource({
            transport: {
                read: function (options) {
                    $.ajax({
                        type: "GET",

                        url: "../ProductRequestGrid/GetProducts",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify({ key: "value" }),
                        success: function (data) {
                            options.success(data);
                        }
                    });
                }
            }
        });
        var departmentdataSource = new kendo.data.DataSource({
            transport: {
                read: function (options) {
                    $.ajax({
                        type: "GET",

                        url: "../ProductRequestGrid/GetDepartments",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify({ key: "value" }),
                        success: function (data) {
                            options.success(data);
                        }
                    });
                }
            }
        });
        var projectManagerdataSource = new kendo.data.DataSource({
            transport: {
                read: function (options) {
                    $.ajax({
                        type: "GET",

                        url: "../ProductRequestGrid/GetProjectManagers",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify({ key: "value" }),
                        success: function (data) {
                            options.success(data);
                        }
                    });
                }
            }
        });
        var leadDevelopersdataSource = new kendo.data.DataSource({
            transport: {
                read: function (options) {
                    $.ajax({
                        type: "GET",

                        url: "../ProductRequestGrid/GetLeadDevelopers",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify({ key: "value" }),
                        success: function (data) {
                            options.success(data);
                        }
                    });
                }
            }
        });
        var paidBydataSource = new kendo.data.DataSource({
            transport: {
                read: function (options) {
                    $.ajax({
                        type: "GET",

                        url: "../ProductRequestGrid/PaidBy",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify({ key: "value" }),
                        success: function (data) {
                            options.success(data);
                        }
                    });
                }
            }
        });

        function dateTimeEditor(container, options) {
            $('<input data-text-field="' + options.field + '" data-value-field="' + options.field + '" data-bind="value:' + options.field + '" data-format="' + options.format + '"/>')
            .appendTo(container)
            .kendoDateTimePicker({});
        }
        $("#ProductRequestGrid").kendoGrid({
            dataSource: dataSource2,
            scrollable: true,
            height: "300px",
            toolbar: [{ name: "create", text: "Create Projects" }, "excel"], //, "save", "cancel"],
            excel: {
                allPages: true,
                fileName: "ProjectsExport.xlsx"
            },
            pageable: true,
            scrollable: true,
            height: 250,
            columns: [

    { field: "contracts", title: "Contracts", filterable: false, width: "7em", template: "<a onclick=\"showServiceContracts('#=id #',this,'" + companyId + "');\"style=\"cursor: pointer;\"> View</a>" },
        { field: "task", title: "Tasks", filterable: false, width: "5em", template: "<a onclick=\"showTasks('#=id #',this,'" + companyId + "');\"style=\"cursor: pointer;\"> View</a>" },
       { title: "Reports", filterable: false, width: "6em", template: "<a onclick=\"showReport('#=id #',this,'" + companyId + "');\"style=\"cursor: pointer;\"> View</a>" },
        { title: "Send Report", filterable: false, width: "7em", template: "<a onclick=\"GetContactsToSendReport('#=id #','" + companyId + "');\"style=\"cursor: pointer;\"> View</a>" },

            { field: "name", title: "Project Name *", filterable: true, width: "10em" },
            { field: "product", title: "Product *", filterable: true, editor: productsDropDownEditor, width: "8em" },
            { field: "depCode", title: "Department *", hidden: true, editor: departmentDropDownEditor, filterable: false, width: "10em" },
            { field: "projectManagerName", title: "ProjectManager *", hidden: true, editor: projectManagerDropDownEditor, filterable: false, width: "12em" },
            { field: "leadDeveloperName", title: "Lead Developer *", filterable: true, editor: leadDevelopersDropDownEditor, width: "12em" },
             { field: "daysToFinish", title: "Days To Finish", filterable: true, width: "10em" },
           { field: "depositAmount", title: "Deposit", format: "{0:c}", hidden: true },

          { field: "estimatedCost", title: "Estimated Cost", format: "{0:c}", width: "10em" },
             { field: "actualAmount", title: "Actual Cost", format: "{0:c}", hidden: true, width: "6em" },
                  { field: "statusName", title: "Status *", editor: statusDropDownEditor, width: "8em" },
                   {
                       field: "paidInFull", title: "Full Paid ?", template: '<input type="checkbox" #=paidInFull ? \'checked="checked"\' : "" # class="chkbx" onclick="return false;" />',
                       filterable: {
                           messages: {
                               isTrue: "Active", // sets the text for "isTrue" radio button
                               isFalse: "Inactive",
                           }
                       },
                       width: "10em"
                   },
                           {
                               title: "File Upload", width: "20em",

                               template: "<input type='button' value='Upload File' onclick='ShowProjectFileUpload(#=id#)' />"

                           },
     {
         title: "UploadedFiles", width: "20em",
         template: "<input type='button' value='Show Upload File' onclick='showProjectUploadFiles(#=id#)' />"
     },

                   {
                       field: "taskScheduleComplete", title: "Task Schedule Complete  ?", template: '<input type="checkbox" #=taskScheduleComplete ? \'checked="checked"\' : "" # class="chkbx" onclick="return false;" />',
                       filterable: {
                           messages: {
                               isTrue: "Active", // sets the text for "isTrue" radio button
                               isFalse: "Inactive",
                           }
                       },
                       width: "12em"
                   },

                     { field: "paidByName", title: "Paid By *", editor: paidByDropDownEditor, width: "9em" },

                        { field: "CommEmployee", title: "InvolvedEmployees *", editor: invlouedEmployeeDropDownEditor, width: "10em" },
                    {
                        field: "contractSentDate", title: "Contract Sent", hidden: true, filterable: false, format: "{0:MM/dd/yyyy HH:mm tt}",
                        editor: dateTimeEditor,
                        filterable: {
                            ui: "datetimepicker"
                        }
                    },
                      {
                          field: "contractSignedDate", title: "Contract Signed", hidden: true, filterable: false, format: "{0:MM/dd/yyyy HH:mm tt}",
                          editor: dateTimeEditor,
                          filterable: {
                              ui: "datetimepicker"
                          }
                      },
                         {
                             field: "depositReceivedDate", title: "Deposit Received", hidden: true, filterable: false, format: "{0:MM/dd/yyyy HH:mm tt}",
                             editor: dateTimeEditor,
                             filterable: {
                                 ui: "datetimepicker"
                             }
                         },
                            {
                                field: "startDate", title: "Start Date", filterable: false, editable: true, format: "{0:MM/dd/yyyy HH:mm tt}",
                                editor: dateTimeEditor, width: "8em",
                                filterable: {
                                    ui: "datetimepicker"
                                }
                            },
                               {
                                   field: "expectedDeliveryDate", title: "Expected Delivery", filterable: false, format: "{0:MM/dd/yyyy HH:mm tt}",
                                   editor: dateTimeEditor, width: "8em",
                                   filterable: {
                                       ui: "datetimepicker"
                                   }
                               },

                                {
                                    field: "deliveryDate", title: "Delivery", hidden: true, filterable: false, format: "{0:MM/dd/yyyy HH:mm tt}",
                                    editor: dateTimeEditor,
                                    filterable: {
                                        ui: "datetimepicker"
                                    }
                                },

                                 {
                                     field: "goLiveDate", title: "Go Live", hidden: true, editable: true, filterable: false, format: "{0:MM/dd/yyyy HH:mm tt}",
                                     editor: dateTimeEditor,
                                     filterable: {
                                         ui: "datetimepicker"
                                     }
                                 },

                                 {
                                     field: "estimateDate", title: "Estimated Date", hidden: true, editable: true, filterable: false, format: "{0:MM/dd/yyyy HH:mm tt}",
                                     editor: dateTimeEditor, width: "8em",
                                     filterable: {
                                         ui: "datetimepicker"
                                     }
                                 },


                 {
                     field: "note", title: "Notes", width: "200px",
                     attributes: {
                         style: 'white-space: nowrap '
                     },
                     editor: function (container, options) {
                         $('<textarea data-bind="value: ' + options.field + '" cols="20" rows="10"></textarea>').appendTo(container);
                     }
                 },

          {
              title: "&nbsp;",
              width: "10em",

              command: [

                  "edit",
                  {
                      name: "Delete",


                      click: function (e) {

                          var tr = $(e.target).closest("tr"); //get the row for deletion
                          var dataItem = this.dataItem(tr); //get the row data so it can be referred later
                          //see what is coming in dataItem
                          //if (dataItem.QuestionAnswers.length > 0) {
                          //    $("#delValidation").addClass('in')
                          //}
                          //else {

                          deleteTopicConfirmation(e, this);
                          //   }
                          return false;
                      }
                  }
              ]
          }
            ],
            filterable: {
                extra: false,
                operators: {
                    string: {
                        eq: "Is equal to",
                        neq: "Is not equal to",
                        contains: "Contains"
                    }
                }
            },

            editable: "popup",

            sortable: {
                mode: "single",
                allowUnsort: false
            },
            selectable: true,
            edit: function () {
                //   e.container.find(".k-edit-label:nth-child(3)").hide();
                gridInEditMode = true;
            },
            excelExport: function (e) {
                for (var i = 0; i < e.workbook.sheets[0].columns.length; i++) {
                    e.workbook.sheets[0].columns[i].autoWidth = true;
                }
            },
            cancel: function () {
                gridInEditMode = false;
            },
            edit: function (e) {
                debugger;
                e.container.find(".k-edit-label:nth-child(1)").hide();
                e.container.find(".k-edit-field:nth-child(1)").hide();
                e.container.find(".k-edit-label:nth-child(2)").hide();
                e.container.find(".k-edit-field:nth-child(2)").hide();
                e.container.find(".k-edit-label:nth-child(3)").hide();
                e.container.find(".k-edit-field:nth-child(3)").hide();
                e.container.find(".k-edit-label:nth-child(4)").hide();
                e.container.find(".k-edit-field:nth-child(4)").hide();
                e.container.find(".k-edit-label:nth-child(5)").hide();
                e.container.find(".k-edit-field:nth-child(5)").hide();
                e.container.find(".k-edit-label:nth-child(6)").hide();
                e.container.find(".k-edit-field:nth-child(6)").hide();
                e.container.find(".k-edit-label:nth-child(7)").hide();
                e.container.find(".k-edit-field:nth-child(8)").hide();

                e.container.find(".k-edit-label:nth-child(31)").hide();
                e.container.find(".k-edit-field:nth-child(32)").hide();
                e.container.find(".k-edit-label:nth-child(33)").hide();
                e.container.find(".k-edit-field:nth-child(34)").hide();
                gridInEditMode = true;
                //e.container.find("input:first").hide();
                editedUID = e.model.uid;
                assignedEmployeeIdVar = e.model.CommEmployeeIds;
                $('<a href="../AddProduct/ProductHistory"><img id="theImg" src="https://cdn0.iconfinder.com/data/icons/16x16-free-toolbar-icons/16/13.png" /></a>').insertAfter($("#ProductValue").parent());
                $('<a href="../AddDepartment/DepartmentHistory"><img id="theImg" src="https://cdn0.iconfinder.com/data/icons/16x16-free-toolbar-icons/16/13.png" /></a>').insertAfter($("#departmentId").parent());


            }
        });




        $("#ProductRequestGrid").kendoTooltip({
            filter: "td:nth-child(27)", //this filter selects the second column's cells
            position: "right",
            content: function (e) {
                var target = e.target;
                return $(target).text();

            }
        }).data("kendoTooltip");

        dataSource2.bind("requestEnd", showSuccessMessage);
        $(".close").click(function () {
            $(this).parent().removeClass('in');
        });
        function showSuccessMessage(e) {
            if (e.type === "update" || e.type === "create") {
                gridInEditMode = false;
                $("#saveConfirm").addClass('in');
                e.sender.read();
            }
        }
        function productsDropDownEditor(container, options) {

            $('<input  required="required" name="product" id="ProductValue" data-text-field="product" data-value-field="id"  data-bind="value:productId"/>').appendTo(container).kendoDropDownList({
                autoBind: true,
                dataValueField: "id",
                dataTextField: "product",
                optionLabel: "select a product",
                dataSource: productsdataSource
            });
            $('<span class="k-invalid-msg" data-for="product"></span>').appendTo(container);

        }
        function invlouedEmployeeDropDownEditor(container, options) {
            $('<input   name="CommEmployee" id="invlouedEmployeeId"  data-bind="value:CommEmployeeIds" />').appendTo(container).kendoDropDownList({
                autoBind: false,
                dataValueField: "id",
                dataTextField: "InvoluedEname",
                dataSource: involuedEmployees,
                template: "<input type='checkbox' id='chk_AssEmp_#=data.id #' onclick='UpdateIdinIsAssEmp(this);' value='#=data.id #' name='chk_AssEmp' />" + " " + "${ data.InvoluedEname }",
                close: function (e) {
                    if (IsAssEmpChecked == true) {
                        IsAssEmpChecked = false;
                        e.preventDefault();
                    }
                    else {
                        var allVals = [];
                        $("input[id*='chk_AssEmp']:checked").each(function () {
                            allVals.push($(this).val());
                        });

                        var gridList = $("#ProductRequestGrid").data("kendoGrid").dataSource.data();
                        for (var i = 0; i < gridList.length; i++) {
                            if (gridList[i].uid == editedUID) {
                                gridList[i].CommEmployeeIds = allVals.join(",");
                                break;
                            }
                        }

                        e.sender.text(allVals.length + " item(s) selected");
                    }
                },
                change: function (e) {
                    e.sender.value(null);
                },
                dataBound: function (e) {
                    //alert("assignedEmployeeIdVar");
                    var count = 0;
                    if (assignedEmployeeIdVar) {
                        assignedEmployeeIdVar = "," + assignedEmployeeIdVar + ",";
                        $("input[id*='chk_AssEmp']").each(function () {

                            if (assignedEmployeeIdVar.indexOf("," + $(this).val() + ",") != -1) {

                                $(this).attr('checked', 'checked');
                                count++;
                            }
                        });
                        assignedEmployeeIdVar = null;
                        e.sender.text(count + " item(s) selected");
                    }
                },
            });

        }
        function departmentDropDownEditor(container, options) {
            $('<input  required="required" name="depCode" id="departmentId" data-text-field="depCode" data-value-field="departmentId" data-bind="value:departmentId"/>').appendTo(container).kendoDropDownList({
                autoBind: true,
                dataValueField: "departmentId",
                dataTextField: "depCode",
                optionLabel: "select a department",
                dataSource: departmentdataSource

            });
            $('<span class="k-invalid-msg" data-for="depCode"></span>').appendTo(container);
        }
        function projectManagerDropDownEditor(container, options) {
            $('<input   id="ManagerId" data-text-field="projectManagerName" data-value-field="id"  data-bind="value:projectManagerId"/>').appendTo(container).kendoDropDownList({
                autoBind: true,
                dataValueField: "id",
                optionLabel: "select project manager",
                dataTextField: "projectManagerName",
                dataSource: projectManagerdataSource

            });


        }
        function leadDevelopersDropDownEditor(container, options) {
            $('<input   id="leaddeveloper" data-text-field="leadDeveloperName" data-value-field="id"  data-bind="value:leadProgrammerId"/>').appendTo(container).kendoDropDownList({
                autoBind: true,
                dataValueField: "id",
                dataTextField: "leadDeveloperName",
                optionLabel: "select lead developer",
                dataSource: leadDevelopersdataSource

            });

        }
        function paidByDropDownEditor(container, options) {
            $('<input  required="required" name="paidByName" id="paidId" data-text-field="paidByName" data-value-field="id" data-bind="value:paidById"/>').appendTo(container).kendoDropDownList({
                autoBind: true,
                dataValueField: "id",
                dataTextField: "paidByName",
                dataSource: paidBydataSource

            });
            $('<span class="k-invalid-msg" data-for="paidByName"></span>').appendTo(container);
        }
        function statusDropDownEditor(container, options) {
            $('<input   required="required" name="statusName" id="leaddeveloper" data-text-field="statusName" data-value-field="status"  data-bind="value:statusId"/>').appendTo(container).kendoDropDownList({
                autoBind: true,
                dataValueField: "status",
                dataTextField: "statusName",
                optionLabel: "select status",
                dataSource: statusdatasource

            });
            $('<span class="k-invalid-msg" data-for="statusName"></span>').appendTo(container);
        }


        function deleteTopicConfirmation(e, widget) {
            var grid = $('#ProductRequestGrid').data("kendoGrid");
            deleteConfirmation(e, widget, grid);
        }

        function deleteConfirmation(e, widget, grid) {

            var currentRow = $(e.target).closest("tr"); //get the row for deletion

            var currentRowData = widget.dataItem(currentRow); //get the row data so it can be  referred later

            var kendoWindow = $("<div />").kendoWindow({

                title: "Confirmation",
                resizable: true,
                modal: true,
                width: "400px",
                deactivate: function () {
                    $('.k-window, .k-overlay').remove();
                }
            });

            kendoWindow.data("kendoWindow")

                .content($("#delete-confirmation").html())

                .center().open();

            kendoWindow

                .find(".delete-confirm,.delete-cancel")
                .click(function () {
                    if ($(this).hasClass("delete-confirm")) {

                        grid.dataSource.remove(currentRowData);

                        grid.dataSource.sync();

                    }

                    $(this).closest("[data-role=window]").kendoWindow("close");

                });

        }
    }

    function ShowProjectFileUpload(id) {
        HideAllUplods();
        $("#ProjectUpload").show();

        $("#hdnProject").val(id);
    }

</script>

@* ...
    Show Company Sales

*@

<script>
    var leadContactId = 0;
    function showSalesLead(companyId, e) {
        var gridInEditMode = false;
        HideAllUplods();
        $('#addcompanyGrid tr.k-state-selected').removeClass('k-state-selected');
        var row = $(e).closest("tr");
        row.addClass("k-state-selected");
        $('#SalesLeadGrid').show();
        $('#ProductRequestGrid').hide();
        $('#TaskGrid').hide();
        $('#SubTaskGrid').hide();
        $('#CompanyContactGrid').hide();
        $('#companyofficegrid').hide();
        $('#CompanyHistoryGrid').hide();
        $('#ServiceContractGrid').hide();
        $("#MessageGrid").hide();
        $('#SalesLeadGrid').empty();
        var SalesGridDataSource = new kendo.data.DataSource({

            transport: {
                read: function (options) {

                    $.ajax({
                        type: "POST",
                        url: "../SalesLead/GetSalesLead",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        cache: false,
                        data: JSON.stringify({ id: companyId }),
                        success: function (data) {
                            debugger;
                            console.log(data);
                            options.success(data);
                        },

                        error: function (request, status, error) {
                            debugger;
                            alert(request.responseText);
                        }
                    });
                },
                create: function (options) {

                    var SalesLeadVM = new Object();
                    SalesLeadVM.id = options.data.id;

                    SalesLeadVM.companyId = options.data.companyId;
                    SalesLeadVM.companyId = companyId;
                    if (options.data.productId)
                        SalesLeadVM.productId = options.data.productId.id;


                    SalesLeadVM.leadContactId = leadContactId;

                    debugger;
                    //console.log("options.data.contactId" + options.data.contactId)
                    //console.log("options.data.contactId.ctId" + options.data.contactId.ctId)

                    if ((typeof (options.data.contactId) != "undefined") && (options.data.contactId != null)) {
                        debugger;
                        SalesLeadVM.contactId = options.data.contactId.ctId;
                    }



                    SalesLeadVM.startDate = options.data.startDate;

                    SalesLeadVM.product = options.data.productId.product





                    SalesLeadVM.loggedOwner = options.data.loggedOwner;
                    SalesLeadVM.numberOfEmployees = options.data.numberOfEmployees;
                    SalesLeadVM.annualRevenue = options.data.annualRevenue;
                    SalesLeadVM.dateOpened = options.data.dateOpened;
                    SalesLeadVM.dateClosed = options.data.dateClosed;
                    SalesLeadVM.daysOpened = options.data.daysOpened;
                    SalesLeadVM.opportunity = options.data.opportunity;
                    SalesLeadVM.daysCal = options.data.daysCal;

                    SalesLeadVM.contractSentDate = options.data.contractSentDate;
                    SalesLeadVM.contractSignedDate = options.data.contractSignedDate;
                    SalesLeadVM.depositReceivedDate = options.data.depositReceivedDate;
                    SalesLeadVM.deposit = options.data.deposit;

                    SalesLeadVM.monthlyDollar = options.data.monthlyDollar;
                    SalesLeadVM.setupDollar = options.data.setupDollar;



                    SalesLeadVM.estimatedCost = options.data.estimatedCost;
                    SalesLeadVM.actualCost = options.data.actualCost;
                    SalesLeadVM.estimateDate = options.data.estimateDate;

                    SalesLeadVM.notes = options.data.notes;

                    $.ajax({
                        type: "POST",
                        url: "/SalesLead/CreateSalesLead",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify(SalesLeadVM),
                        success: function (data) {
                            if (data.Message) {
                                alert(data.Message);
                            }
                            options.success(data);
                        }
                    });
                },
                update: function (options) {
                    debugger;
                    options.data.companyId = companyId;
                    var SalesLeadVM = new Object();
                    SalesLeadVM.id = options.data.id;
                    SalesLeadVM.companyId = companyId;
                    SalesLeadVM.productId = options.data.productId;
                    if (leadContactId != 0)
                        SalesLeadVM.leadContactId = leadContactId;
                    else
                        SalesLeadVM.leadContactId = options.data.leadContactId;

                    SalesLeadVM.contactId = options.data.contactId

                    SalesLeadVM.startDate = options.data.startDate;
                    SalesLeadVM.loggedOwner = options.data.loggedOwner;
                    SalesLeadVM.numberOfEmployees = options.data.numberOfEmployees;
                    SalesLeadVM.annualRevenue = options.data.annualRevenue;
                    SalesLeadVM.dateOpened = options.data.dateOpened;
                    SalesLeadVM.dateClosed = options.data.dateClosed;
                    SalesLeadVM.daysOpened = options.data.daysOpened;
                    SalesLeadVM.opportunity = options.data.opportunity;
                    SalesLeadVM.daysCal = options.data.daysCal;

                    SalesLeadVM.contractSentDate = options.data.contractSentDate;
                    SalesLeadVM.contractSignedDate = options.data.contractSignedDate;
                    SalesLeadVM.depositReceivedDate = options.data.depositReceivedDate;
                    SalesLeadVM.deposit = options.data.deposit;

                    SalesLeadVM.leadcontactname = options.data.leadcontactname;

                    SalesLeadVM.product = options.data.product;



                    SalesLeadVM.estimatedCost = options.data.estimatedCost;
                    SalesLeadVM.actualCost = options.data.actualCost;
                    SalesLeadVM.estimateDate = options.data.estimateDate;

                    SalesLeadVM.monthlyDollar = options.data.monthlyDollar;
                    SalesLeadVM.setupDollar = options.data.setupDollar;

                    SalesLeadVM.notes = options.data.notes;
                    $.ajax({
                        type: "POST",
                        url: "/SalesLead/UpdateSalesLead",
                        dataType: 'json',
                        data: JSON.stringify(SalesLeadVM),
                        contentType: "application/JSON",
                        success: function (data) {
                            if (data.Message) {
                                alert(data.Message);
                            }
                            options.success(data);
                        }
                    });
                },
                destroy: function (options) {

                    $.ajax({
                        type: "POST",
                        url: "../SalesLead/DeleteSalesLead",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify({ id: options.data.id }),

                        success: function (data) {
                            debugger;
                            options.success(data);
                        }
                    });
                },
                parameterMap: function (options) {
                    return kendo.stringify(options); // kendo.stringify serializes to JSON string
                }
            },
            schema: {
                model: {
                    id: "id",
                    fields: {
                        id: {
                            editable: false, nullable: true,
                            type: "int"
                        },
                        loggedOwner:
                            {
                                defaultValue: "@User.Identity.Name",
                                type: "string"
                            },
                        name: {
                            type: "string"
                        },
                        leadcontactname:
                            {
                                type: "string"
                            },
                        companycontactname:
                         {
                             type: "string"
                         },

                        companyId: {
                            type: "int",
                            // defaultValue: companyId
                        },

                        product: {
                            type: "string"

                        },
                        daysOpened:
                            {
                                type: "int"

                            },
                        monthlyDollar:
                          {
                              type: "decimal"
                          },
                        setupDollar:
                                        {
                                            type: "decimal"
                                        },
                        opportunity: {
                            type: "string"
                            // validation: { required: true }
                        },

                        notes:
                            {
                                type: "string"
                            },
                        numberOfEmployees: {
                            type: "int"

                        },
                        annualRevenue: {
                            type: "decimal"

                        },
                        deposit: {
                            editable: true,
                            type: "int"
                        },

                        estimatedCost: {
                            type: "int",

                        },
                        actualCost: {
                            type: "int",
                            //  validation: { required: true }
                        },
                        dateOpened: {
                            type: "date",
                            //  validation: { required: true },
                            nullable: true,
                            value: "",
                            defaultOption: null
                        },
                        dateClosed: {
                            type: "date",
                            //  validation: { required: true },
                            nullable: true,
                            value: "",
                            defaultOption: null
                        },
                        code:
                            {
                                type: "string"
                            },


                        contractSentDate: {
                            type: "date",
                            //  validation: { required: true },
                            nullable: true,
                            value: "",
                            defaultOption: null
                        },
                        contractSignedDate: {
                            type: "date",
                            //  validation: { required: true },
                            nullable: true,
                            value: "",
                            defaultOption: null
                        },

                        depositReceivedDate:
                            {
                                type: "date",
                                //  validation: { required: true },
                                nullable: true,
                                value: "",
                                defaultOption: null
                            },

                        startDate: {
                            type: "date",
                            //  validation: { required: true },
                            nullable: true,
                            value: "",
                            defaultOption: null
                        },
                        contactId:
                        {
                            type: "int"
                        },
                        selected: { type: "string" },

                        error: function (a) {
                            $('#SalesLeadGrid').data("kendoGrid").cancelChanges();
                        },
                    }
                }
            }

        });

        var productsdataSource = new kendo.data.DataSource({
            transport: {
                read: function (options) {
                    $.ajax({
                        type: "GET",
                        url: "../ProductRequestGrid/GetProducts",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify({ key: "value" }),
                        success: function (data) {
                            options.success(data);
                        }
                    });
                }
            }
        });


        var companycontactsdatasource = new kendo.data.DataSource({
            transport: {
                read: function (options) {
                    $.ajax({
                        type: "POST",

                        url: "../CommunicationMessageGrid/GetAllCompanyContacts",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify({ id: companyId }),
                        success: function (data) {
                            options.success(data);
                        }
                    });
                }
            }
        });
        var allcontactsdatasource = new kendo.data.DataSource({
            transport: {
                read: function (options) {
                    $.ajax({
                        type: "GET",
                        url: "../CommunicationMessageGrid/GetAllContacts",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        success: function (data) {
                            options.success(data);
                        }
                    });
                }
            }
        });


        function dateTimeEditor(container, options) {
            $('<input data-text-field="' + options.field + '" data-value-field="' + options.field + '" data-bind="value:' + options.field + '" data-format="' + options.format + '"/>')
            .appendTo(container)
            .kendoDateTimePicker({});
        }
        $("#SalesLeadGrid").kendoGrid({
            dataSource: SalesGridDataSource,
            scrollable: true,
            height: "300px",
            toolbar: [{ name: "create", text: "Create sales" }, "excel"], //, "save", "cancel"],
            excel: {
                allPages: true,
                fileName: "SalesProjectExport.xlsx"
            },
            pageable: true,
            scrollable: true,
            height: 250,
            columns: [
            { field: "loggedOwner", title: "Created User", filterable: true, width: "10em", editable: true },
           { field: "leadcontactname", title: "Lead Name *", filterable: false, width: "10em", editor: allcontactsAutoCompleteEditor, editable: true },
            { field: "ccontactname", title: "Company Conatact ", editor: companycontactnameDropDownEditor, filterable: true, width: "12em" },
            { field: "product", title: "Product *", filterable: true, editor: productsDropDownEditor, width: "8em" },


           { field: "numberOfEmployees", title: "Number Of Employee", width: "12em" },
             { field: "annualRevenue", title: "Annual Revenue", format: "{0:c}", width: "10em" },
       { field: "monthlyDollar", title: "Monthly Dollar", format: "{0:c}", width: "10em" },
       { field: "setupDollar", title: "Set Up Dollar", format: "{0:c}", width: "10em" },
               { field: "deposit", title: "Deposit", format: "{0:c}", hidden: true },

                 { field: "opportunity", title: "Opportunity", editor: oportunityDropdownEditor, width: "10em" },

          { field: "estimatedCost", title: "Estimated Cost", format: "{0:c}", width: "10em" },
             { field: "actualCost", title: "Actual Cost", format: "{0:c}", width: "10em" },
              {
                  field: "dateOpened", title: "Date Opened *", width: "10em", filterable: false, format: "{0:MM/dd/yyyy HH:mm tt}",
                  editor: dateTimeEditor,
                  filterable: {
                      ui: "datetimepicker"
                  }
              },
                 {
                     field: "dateClosed", title: "Date Closed", width: "10em", filterable: false, format: "{0:MM/dd/yyyy HH:mm tt}",
                     editor: dateTimeEditor,
                     filterable: {
                         ui: "datetimepicker"
                     }
                 },
                   { field: "daysOpened", title: "How Many Days Opened", filterable: true, width: "12em" },
                    {
                        field: "contractSentDate", title: "Contract Sent", width: "10em", filterable: false, format: "{0:MM/dd/yyyy HH:mm tt}",
                        editor: dateTimeEditor,
                        filterable: {
                            ui: "datetimepicker"
                        }
                    },
                      {
                          field: "contractSignedDate", title: "Contract Signed", hidden: true, filterable: false, format: "{0:MM/dd/yyyy HH:mm tt}",
                          editor: dateTimeEditor,
                          filterable: {
                              ui: "datetimepicker"
                          }
                      },
                         {
                             field: "depositReceivedDate", title: "Deposit Received", hidden: true, filterable: false, format: "{0:MM/dd/yyyy HH:mm tt}",
                             editor: dateTimeEditor,
                             filterable: {
                                 ui: "datetimepicker"
                             }
                         },
                            {
                                field: "startDate", title: "Start Date", filterable: false, editable: true, format: "{0:MM/dd/yyyy HH:mm tt}",
                                editor: dateTimeEditor, width: "8em",
                                filterable: {
                                    ui: "datetimepicker"
                                }
                            },
                            {
                                title: "File Upload", width: "20em",
                                //template: "<input type='file' name='files' id='files',data-role='upload', multiple='multiple', autocomplete='off'/>",
                                template: "<input type='button' value='Upload File' onclick='ShowFileUpload(#=id#)' />"
                                //editor: generateButton
                            },
     {
         title: "UploadedFiles", width: "20em",
         template: "<input type='button' value='Show Upload File' onclick='showSalesUploadFiles(#=id#)' />"
     },

                 {
                     field: "notes", title: "Notes", width: "200px", editor: function (container, options) {
                         $('<textarea data-bind="value: ' + options.field + '" cols="20" rows="10"></textarea>').appendTo(container);
                     }
                 },


          {
              title: "&nbsp;",
              width: "10em",

              command: [

                  "edit",
                  {
                      name: "Delete",


                      click: function (e) {

                          var tr = $(e.target).closest("tr"); //get the row for deletion
                          var dataItem = this.dataItem(tr); //get the row data so it can be referred later
                          //see what is coming in dataItem
                          //if (dataItem.QuestionAnswers.length > 0) {
                          //    $("#delValidation").addClass('in')
                          //}
                          //else {

                          deleteTopicConfirmation(e, this);
                          //   }
                          return false;
                      }
                  }
              ]
          }
            ],
            filterable: {
                extra: false,
                operators: {
                    string: {
                        eq: "Is equal to",
                        neq: "Is not equal to",
                        contains: "Contains"
                    }
                }
            },

            editable: "popup",

            sortable: {
                mode: "single",
                allowUnsort: false
            },
            selectable: true,

            edit: function (e) {
                gridInEditMode = true;
                e.container.find(".k-edit-label:nth-child(39)").hide();
                e.container.find(".k-edit-field:nth-child(40)").hide();
                e.container.find(".k-edit-label:nth-child(41)").hide();
                e.container.find(".k-edit-field:nth-child(42)").hide();

            },
            excelExport: function (e) {
                for (var i = 0; i < e.workbook.sheets[0].columns.length; i++) {
                    e.workbook.sheets[0].columns[i].autoWidth = true;
                }
            },
            cancel: function () {
                gridInEditMode = false;
            },
            save: function (e) {
                console.log(e.model.dateClosed);
                if ((e.model.dateClosed < e.model.dateOpened) && (e.model.dateClosed != null)) {
                    alert('Date closed is smaller than Date open');
                    e.preventDefault();
                }
            },
        });

        $("#SalesLeadGrid").kendoTooltip({
            filter: "td:nth-child(23)", //this filter selects the second column's cells
            position: "left",
            content: function (e) {
                var target = e.target;
                return $(target).text();

            }
        }).data("kendoTooltip");

        function productsDropDownEditor(container, options) {

            $('<input required="required" name="product" id="ProductValue" data-text-field="product" data-value-field="id"  data-bind="value:productId"/>').appendTo(container).kendoDropDownList({
                autoBind: true,
                dataValueField: "id",
                optionLabel: "select a product",
                dataTextField: "product",
                dataSource: productsdataSource
            });
            $('<span class="k-invalid-msg" data-for="product"></span>').appendTo(container);

        }


        function companycontactnameDropDownEditor(container, options) {

            $('<input  id="companyctId" data-text-field="name" data-value-field="ctId"  data-bind="value:contactId" />').appendTo(container).kendoDropDownList({
                autoBind: true,
                dataValueField: "ctId",
                dataTextField: "name",
                dataSource: companycontactsdatasource,

            });

        }


        function allcontactsAutoCompleteEditor(container, options) {
            leadContactId = 0;

            $('<input  data-text-field="contactname"  data-value-field="id"   data-bind="value:leadcontactname" style="width:245px;"/>')
                .appendTo(container)
                .kendoAutoComplete({
                    headerTemplate: '<div class="AutoCompleteHeader">' +
               '<span style="width:50%;"> Contact info</span>' +
                '<span> | </span>' +
               '<span style="width:50%;"> Company </span>' +
           '</div>',
                    template: '<span class="k-state-default" style="width:50%;">#:data.contactname #</span>' +
                '<span> | </span>' +
                      '<span class="k-state-default" style="width:50%;"> #:data.cpName #</span> ',
                    dataValueField: "id",
                    dataTextField: "contactname",
                    suggest: true,
                    placeHolder: "Enter Caller Name here",
                    filter: "contains",
                    index: 1,
                    height: 400,
                    minLength: 1,
                    dataSource: allcontactsdatasource,
                    select: function (e) {
                        var dataItem = this.dataItem(e.item.index());
                        leadContactId = dataItem.id;
                    }
                });



        }


        function oportunityDropdownEditor(container, options) {
            $('<input id="timeZoneId" data-text-field="dataText" data-value-field="dataText"  data-bind="value:' + options.field + '"/>').appendTo(container).kendoDropDownList({
                autoBind: true,
                dataSource: {
                    data: [{ dataText: "0%", dataValue: "1" },
                        { dataText: "10%", dataValue: "2" },
                        { dataText: "20%", dataValue: "3" },
                        { dataText: "30%", dataValue: "4" },
                     { dataText: "40%", dataValue: "5" },
                        { dataText: "50%", dataValue: "6" },
                        { dataText: "60%", dataValue: "7" },
                    { dataText: "70%", dataValue: "8" },
                    { dataText: "80%", dataValue: "9" },
                   { dataText: "90%", dataValue: "10" },
    { dataText: "100%", dataValue: "11" }]
                }

            });
        }


        function generateButton(container, options) {
            alert(options);
            container.append('<input type="file" name="' + options.field + '" data-type="boolean"/>')
                    .append('<a href="#" id="files" class="k-button k-upload-button"></a>');
        }

        SalesGridDataSource.bind("requestEnd", showSuccessMessage);
        function showSuccessMessage(e) {
            if (e.type === "update" || e.type === "create") {
                gridInEditMode = false;
                $("#saveConfirm").addClass('in');
                e.sender.read();
            }
        }
        $(".close").click(function () {
            $(this).parent().removeClass('in');
        });

        function deleteTopicConfirmation(e, widget) {
            var grid = $('#SalesLeadGrid').data("kendoGrid");
            deleteConfirmation(e, widget, grid);
        }

        function deleteConfirmation(e, widget, grid) {

            var currentRow = $(e.target).closest("tr"); //get the row for deletion

            var currentRowData = widget.dataItem(currentRow); //get the row data so it can be  referred later

            var kendoWindow = $("<div />").kendoWindow({

                title: "Confirmation",
                resizable: true,
                modal: true,
                width: "400px",
                deactivate: function () {
                    $('.k-window, .k-overlay').remove();
                }
            });

            kendoWindow.data("kendoWindow")

                .content($("#delete-confirmation").html())

                .center().open();

            kendoWindow

                .find(".delete-confirm,.delete-cancel")
                .click(function () {
                    if ($(this).hasClass("delete-confirm")) {

                        grid.dataSource.remove(currentRowData);

                        grid.dataSource.sync();

                    }

                    $(this).closest("[data-role=window]").kendoWindow("close");

                });

        }
    }

    function ShowFileUpload(id) {
        HideAllUplods();
        $("#SalesLeadUpload").show();
        $("#hdnSalesLead").val(id);
    }

</script>


@* ...
    Show Project Contracts

*@

<script>
    function showServiceContracts(productRequestId, e, companyId) {
        HideAllUplods();
        $('#ProductRequestGrid tr.k-state-selected').removeClass('k-state-selected');
        var row = $(e).closest("tr");
        row.addClass("k-state-selected");
        $('#ServiceContractGrid').show();
        $('#TaskGrid').hide();
        $('#SubTaskGrid').hide();
        $('#CompanyContactGrid').hide();
        $('#companyofficegrid').hide();
        $('#CompanyHistoryGrid').hide();
        $("#MessageGrid").hide();
        $('#ServiceContractGrid').empty();
        gridInEditMode = false;
        var dataSource = new kendo.data.DataSource({
            transport: {
                read: function (options) {
                    $.ajax({
                        type: "POST",
                        url: "../AddServiceContract/GetServiceContract",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify({ id: productRequestId }),

                        success: function (data) {

                            options.success(data);
                        },

                        error: function (request, status, error) {

                            alert(request.responseText);
                        }
                    });
                },
                create: function (options) {

                    options.data.productRequestId = productRequestId
                    options.data.companyId = companyId
                    //options.data.companyId = companyId
                    $.ajax({
                        type: "POST",
                        url: "/AddServiceContract/CreateServiceContract",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify(options.data),
                        success: function (data) {
                            if (data.Message) {
                                alert(data.Message);
                            }
                            options.success(data);
                        }
                    });
                },
                update: function (options) {
                    $.ajax({
                        type: "POST",
                        url: "../AddServiceContract/UpdateServiceContract",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify(options.data),

                        success: function (data) {
                            if (data.Message) {
                                alert(data.Message);
                            }
                            options.success(data);
                        }
                    });
                },
                destroy: function (options) {
                    $.ajax({
                        type: "POST",
                        url: "../AddServiceContract/DeleteServiceContract",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify({ id: options.data.id }),

                        success: function (data) {

                            options.success(data);
                        }
                    });
                },
                parameterMap: function (options) {
                    return kendo.stringify(options); // kendo.stringify serializes to JSON string
                }
            },
            schema: {
                model: {
                    id: "id",
                    fields: {
                        id: {
                            editable: false, nullable: true,
                            type: "int"
                        },
                        companyId: {
                            type: "int",
                            editable: false
                        },

                        cost: {
                            type: "int"
                        },
                        hourlyRate:
                            {
                                type: "decimal"
                            },
                        hoursPerMonth:
                            {
                                type: "decimal"
                            },
                        productRequestId:
                    {
                        type: "int"
                    },
                        contractorId: {
                            type: "int"
                        },
                        contractLetter: {
                            type: "string"
                        },
                        contractStatus: {
                            type: "string"
                        },
                        note: {
                            type: "string"
                        },
                        relationStart: {
                            type: "date",
                            //  validation: { required: true },
                            nullable: true,
                            value: "",
                            defaultOption: null
                        },
                        renewalDate: {
                            type: "date",
                            //  validation: { required: true },
                            nullable: true,
                            value: "",
                            defaultOption: null
                        },
                        startDate: {
                            type: "date",
                            //  validation: { required: true },
                            nullable: true,
                            value: "",
                            defaultOption: null
                        },
                        endDate:
                            {
                                type: "date",
                                //  validation: { required: true },
                                nullable: true,
                                value: "",
                                defaultOption: null
                            },
                        error: function (a) {

                            $('#ServiceContractGrid').data("kendoGrid").cancelChanges();
                        },
                    }
                }
            }
        });
        function dateTimeEditor(container, options) {
            $('<input data-text-field="' + options.field + '" data-value-field="' + options.field + '" data-bind="value:' + options.field + '" data-format="' + options.format + '"/>')
            .appendTo(container)
            .kendoDateTimePicker({});
        }

        $("#ServiceContractGrid").kendoGrid({
            dataSource: dataSource,
            scrollable: true,
            height: "250px",
            toolbar: [{ name: "create", text: "Add Service Contract" }, "excel"], //, "save", "cancel"],
            excel: {
                allPages: true,
                fileName: "ServiceContractExport.xlsx"
            },
            pageable: true,
            height: 300,
            columns: [
          { field: "hourlyRate", title: "Hourly Rate *", filterable: false, width: "8em" },
            { field: "companyId", editable: false, hidden: true },
          { field: "cost", title: "Cost", format: "{0:c}", width: "8em" },
            { field: "hoursPerMonth", title: "Hours PerMonth *", width: "8em" },
           {
               field: "startDate", title: "Start Date", filterable: false, format: "{0:MM/dd/yyyy HH:mm tt}",
               editor: dateTimeEditor,
               filterable: {
                   ui: "datetimepicker"
               }
           },

                 {
                     field: "endDate", title: "End Date", editable: true, filterable: false, format: "{0:MM/dd/yyyy HH:mm tt}",
                     editor: dateTimeEditor,
                     filterable: {
                         ui: "datetimepicker"
                     }
                 },

                 {
                     field: "renewalDate", title: "Renewal Date", editable: true, filterable: false, format: "{0:MM/dd/yyyy HH:mm tt}",
                     editor: dateTimeEditor, width: "8em",
                     filterable: {
                         ui: "datetimepicker"
                     }
                 },
                   {
                       field: "note", title: "Notes", width: "200px", editor: function (container, options) {
                           $('<textarea data-bind="value: ' + options.field + '" cols="20" rows="10"></textarea>').appendTo(container);
                       }
                   },
          {
              title: "&nbsp;",
              width: "25em",

              command: [

                  "edit",
                  {
                      name: "Delete",


                      click: function (e) {

                          var tr = $(e.target).closest("tr"); //get the row for deletion
                          var dataItem = this.dataItem(tr); //get the row data so it can be referred later
                          //see what is coming in dataItem
                          //if (dataItem > 0) {
                          //    $("#delValidation").addClass('in')
                          //}
                          //else {

                          deleteTopicConfirmation(e, this);
                          ////}
                          return false;
                      }
                  }
              ]
          }
            ],
            filterable: {
                extra: false,
                operators: {
                    string: {
                        eq: "Is equal to",
                        neq: "Is not equal to",
                        contains: "Contains"
                    }
                }
            },

            editable: "popup",
            sortable: {
                mode: "single",
                allowUnsort: false
            },
            edit: function () {
                //  e.container.find(".k-edit-label:nth-child(2)").hide();
                gridInEditMode = true;
            },

            edit: function (e) {
                debugger;

                e.container.find(".k-edit-label:nth-child(3)").hide();
                e.container.find(".k-edit-field:nth-child(4)").hide();

                gridInEditMode = true;

            },

            selectable: true,
            // change: onTopicChange,
            // dataBound: onTopicsGridDataBound,

            cancel: function () {
                gridInEditMode = false;
            }
        });
        function deleteTopicConfirmation(e, widget) {
            var grid = $('#ServiceContractGrid').data("kendoGrid");
            deleteConfirmation(e, widget, grid);
        }

        function deleteConfirmation(e, widget, grid) {

            var currentRow = $(e.target).closest("tr"); //get the row for deletion

            var currentRowData = widget.dataItem(currentRow); //get the row data so it can be  referred later

            var kendoWindow = $("<div />").kendoWindow({

                title: "Confirmation",
                resizable: true,
                modal: true,
                width: "400px",
                deactivate: function () {
                    $('.k-window, .k-overlay').remove();
                }
            });

            kendoWindow.data("kendoWindow")

                .content($("#delete-confirmation").html())

                .center().open();

            kendoWindow

                .find(".delete-confirm,.delete-cancel")
                .click(function () {
                    if ($(this).hasClass("delete-confirm")) {

                        grid.dataSource.remove(currentRowData);

                        grid.dataSource.sync();

                    }

                    $(this).closest("[data-role=window]").kendoWindow("close");

                });

        }
        dataSource.bind("requestEnd", showSuccessMessage);
        function showSuccessMessage(e) {
            if (e.type === "update" || e.type === "create") {
                gridInEditMode = false;
                $("#saveConfirm").addClass('in');
                e.sender.read();
            }
        }
        $(".close").click(function () {
            $(this).parent().removeClass('in');
        });
    }

</script>

@* ...
    Show Project Tasks

*@

<script>
    var TaskID = 0;
    function showTasks(productReqestId, e, companyId) {
        HideAllUplods();
        $('#TaskGrid').show();
        $('#ProductRequestGrid tr.k-state-selected').removeClass('k-state-selected');
        var row = $(e).closest("tr");

        row.addClass("k-state-selected");

        $('#ServiceContractGrid').hide();
        $('#SubTaskGrid').hide();
        $('#CompanyContactGrid').hide();
        $('#companyofficegrid').hide();
        $('#CompanyHistoryGrid').hide();
        $("#MessageGrid").hide();
        $('#TaskGrid').empty();

        var gridInEditMode = false;
        var dataSource = new kendo.data.DataSource({
            transport: {
                read: function (options) {


                    $.ajax({
                        type: "POST",
                        url: "../Task/GetTask",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        cache: false,
                        data: JSON.stringify({ id: productReqestId }),
                        success: function (data) {

                            options.success(data);
                        },

                        error: function (request, status, error) {

                            alert(request.responseText);
                        }
                    });
                },
                create: function (options) {
                    debugger;
                    options.data.productReqestId = productReqestId
                    var TaskViewModel = new Object();
                    TaskViewModel.id = options.data.id;
                    TaskViewModel.productReqestId = productReqestId;
                    TaskViewModel.taskName = options.data.taskName;
                    TaskViewModel.description = options.data.description;

                    TaskViewModel.startDate = options.data.startDate;
                    TaskViewModel.endDate = options.data.endDate;
                    TaskViewModel.modifiedDate = options.data.modifiedDate;

                    TaskViewModel.Gap = options.data.Gap;

                    TaskViewModel.NoOfDays = options.data.NoOfDays;
                    TaskViewModel.Budget = options.data.Budget;
                    TaskViewModel.Notes = options.data.Notes;

                    TaskViewModel.DependtaskName = options.data.DependtaskName;

                    if (options.data.heldContactId)
                        TaskViewModel.heldContactId = options.data.heldContactId.id;



                    if (options.data.statusId)
                        TaskViewModel.statusId = options.data.statusId.status;

                    $.ajax({
                        type: "POST",
                        url: "/Task/Createtask",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        cache: false,
                        data: JSON.stringify(TaskViewModel),
                        success: function (data) {
                            if (data.Message) {
                                alert(data.Message);
                            }
                            options.success(data);
                        }
                    });
                },
                update: function (options) {
                    options.data.productReqestId = productReqestId
                    var TaskViewModel = new Object();
                    TaskViewModel.id = options.data.id;
                    TaskViewModel.taskName = options.data.taskName;
                    TaskViewModel.description = options.data.description;

                    TaskViewModel.startDate = options.data.startDate;
                    TaskViewModel.endDate = options.data.endDate;
                    TaskViewModel.modifiedDate = options.data.modifiedDate;

                    TaskViewModel.Gap = options.data.Gap;

                    TaskViewModel.NoOfDays = options.data.NoOfDays;
                    TaskViewModel.Budget = options.data.Budget;
                    TaskViewModel.Notes = options.data.Notes;
                    TaskViewModel.DependTaskId = options.data.DependTaskId;
                    TaskViewModel.heldContactId = options.data.heldContactId;
                    TaskViewModel.statusId = options.data.statusId;

                    $.ajax({
                        type: "POST",
                        url: "../Task/UpdateTask",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        cache: false,

                        data: JSON.stringify(options.data),

                        success: function (data) {

                            options.success(data);
                        }
                    });
                },
                destroy: function (options) {
                    $.ajax({
                        type: "POST",
                        url: "../Task/DeleteTask",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        cache: false,

                        data: JSON.stringify({ id: options.data.id }),

                        success: function (data) {

                            options.success(data);
                        }
                    });
                },
                parameterMap: function (options) {
                    return kendo.stringify(options); // kendo.stringify serializes to JSON string
                }
            },
            schema: {
                model: {
                    id: "id",
                    fields: {
                        id: {
                            editable: false, nullable: true,
                            type: "int"
                        },
                        subtask:
                        {
                            type: "string"
                        },
                        name:
                    {
                        type: "string"
                    },

                        taskName: {
                            type: "string"
                        },

                        companyId:
                           {
                               type: "int",
                               editable: false,
                               nullable: true
                           },
                        description:
                            {
                                type: "string"
                            },
                        startDate:
                            {
                                type: "date",
                                //  validation: { required: true },
                                nullable: true,
                                value: "",
                                defaultOption: null
                            },

                        endDate:
                            {
                                type: "date",
                                //  validation: { required: true },
                                nullable: true,
                                value: "",
                                defaultOption: null
                            },
                        modifiedDate: {
                            type: "date",
                            //  validation: { required: true },
                            nullable: true,
                            value: "",
                            defaultOption: null
                        },
                        productReqestId:
                    {
                        type: "int"
                    },
                        NoOfDays: {
                            type: "int"
                        },

                        DependtaskName: {
                            type: "string",
                            defaultValue: "None"
                        },
                        Gap: {
                            type: "int"
                        },

                        heldContactName: {
                            type: "string"
                        },
                        Budget: {
                            type: "decimal"
                        },

                        statusName: {
                            type: "string",
                            defaultValue: "Open"

                        },
                        Notes: {
                            type: "string"
                            // validation: { required: true }
                        },
                        error: function (a) {

                            $('#TaskGrid').data("kendoGrid").cancelChanges();
                        },
                    }
                }
            }
        });
        var heldContactdataSource = new kendo.data.DataSource({
            transport: {
                read: function (options) {
                    $.ajax({
                        type: "GET",

                        url: "../ProductRequestGrid/GetHeldEmployee",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify({ key: "value" }),
                        success: function (data) {
                            options.success(data);
                        }
                    });
                }
            }
        });
        var statusdatasource = new kendo.data.DataSource({
            transport: {
                read: function (options) {
                    $.ajax({
                        type: "GET",

                        url: "../ScratchPad/GetStatus",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify({ key: "value" }),
                        success: function (data) {
                            options.success(data);
                        }
                    });
                }
            }
        });
        var dependTasksdatasource = new kendo.data.DataSource({
            transport: {
                read: function (options) {
                    if (TaskID == null) {
                        TaskID = 0;
                    }
                    $.ajax({
                        type: "POST",
                        url: "../Task/GetAllDependentTask",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        cache: false,
                        data: JSON.stringify({ id: TaskID, productReqestId: productReqestId }),
                        success: function (data) {
                            options.success(data);
                        }
                    });
                }
            },
            serverFiltering: true
        });
        function dateTimeEditor(container, options) {
            $('<input data-text-field="' + options.field + '" data-value-field="' + options.field + '" data-bind="value:' + options.field + '" data-format="' + options.format + '"/>')
            .appendTo(container)
            .kendoDateTimePicker({});
        }

        $("#TaskGrid").kendoGrid({
            dataSource: dataSource,
            scrollable: true,
            height: "250px",
            toolbar: [{ name: "create", text: "Add Task" }, "excel"], //, "save", "cancel"],
            excel: {
                allPages: true,
                fileName: "TaskExport.xlsx"
            },
            pageable: true,
            height: 300,
            columns: [
             { field: "subtask", title: "SubTask", filterable: false, width: "6em", template: "<a onclick=\"showSubTask('#=id #',this);\"style=\"cursor: pointer;\"> View</a>" },
             { field: "history", title: "History", filterable: false, width: "6em", template: "<a onclick=\"showTaskHistory('#=id #',this);\"style=\"cursor: pointer;\"> View</a>" },
               { field: "companyId", editable: false, hidden: true },
          { field: "taskName", title: "TaskName *", filterable: false, width: "10em" },
          { field: "description", title: "Description", width: "8em" },

            {
                field: "startDate", title: "Start Date *", filterable: false, format: "{0:MM-dd-yyyy}",
                editor: dateTimeEditor, width: "8em",
                filterable: {
                    ui: "datetimepicker"
                }
            },
            { field: "NoOfDays", title: "Duration*", width: "8em" },
           { field: "DependtaskName", title: "DependTask", editor: dependTaskDropDownEditor, width: "10em" },
              { field: "Gap", title: "Gap", width: "8em" },
                 { field: "heldContactName", title: "Held By *", editor: heldEmployeeDropDownEditor, width: "8em" },

                 {
                     field: "endDate", title: "End Date", editable: true, filterable: false, format: "{0:MM/dd/yyyy}",
                     editor: dateTimeEditor, width: "8em",
                     filterable: {
                         ui: "datetimepicker"
                     }
                 },
                 {
                     field: "modifiedDate", title: "Modified Date", editable: true, format: "{0:MM/dd/yyyy HH:mm tt}",
                     editor: dateTimeEditor, width: "8em",
                     filterable: {
                         ui: "datetimepicker"
                     }
                 },

                   { field: "Budget", title: "Budget", format: "{0:c}", width: "8em" },
                    {
                        field: "Notes", title: "Notes", width: "200px", editor: function (container, options) {
                            $('<textarea data-bind="value: ' + options.field + '" cols="20" rows="10"></textarea>').appendTo(container);
                        }
                    },
                     { field: "statusName", title: "Status*", editor: statusDropDownEditor, width: "8em" },
          {
              title: "&nbsp;",
              width: "20em",

              command: [
                  "edit",
                  {
                      name: "Delete",
                      click: function (e) {

                          var tr = $(e.target).closest("tr"); //get the row for deletion
                          var dataItem = this.dataItem(tr); //get the row data so it can be referred later
                          //see what is coming in dataItem
                          //if (dataItem > 0) {
                          //    $("#delValidation").addClass('in')
                          //}
                          //else {

                          deleteTopicConfirmation(e, this);
                          ////}
                          return false;
                      }
                  }
              ]
          }
            ],
            filterable: {
                extra: false,
                operators: {
                    string: {
                        eq: "Is equal to",
                        neq: "Is not equal to",
                        contains: "Contains"
                    }
                }
            },
            editable: "popup",
            edit: function () {
                //  e.container.find(".k-edit-label:nth-child(2)").hide();
                gridInEditMode = true;
            },
            excelExport: function (e) {
                for (var i = 0; i < e.workbook.sheets[0].columns.length; i++) {
                    e.workbook.sheets[0].columns[i].autoWidth = true;
                }
            },

            edit: function (e) {
                debugger;
                TaskID = e.model.id;
                e.container.find(".k-edit-label:nth-child(1)").hide();
                e.container.find(".k-edit-field:nth-child(2)").hide();
                e.container.find(".k-edit-label:nth-child(3)").hide();
                e.container.find(".k-edit-field:nth-child(4)").hide();
                e.container.find(".k-edit-label:nth-child(5)").hide();
                e.container.find(".k-edit-field:nth-child(6)").hide();
                gridInEditMode = true;


            },
            sortable: {
                mode: "single",
                allowUnsort: false
            },
            selectable: true,
            cancel: function (e) {
                gridInEditMode = false;
                var dropdownlist = $("#leaddeveloper").data("kendoDropDownList");
                dropdownlist.destroy();
                //dropdownlist.wrapper.remove();
                dropdownlist.element.removeData("kendoDropDownList");
            },



        });
        function heldEmployeeDropDownEditor(container, options) {

            $('<input id="ManagerId" data-text-field="heldContactName" data-value-field="id"  data-bind="value:heldContactId"/>').appendTo(container).kendoDropDownList({
                autoBind: true,

                dataSource: heldContactdataSource

            });
        }
        function statusDropDownEditor(container, options) {
            $('<input id="leaddeveloper" data-text-field="statusName" data-value-field="status" data-bind="value:statusId"/>').appendTo(container).kendoDropDownList({
                autoBind: true,

                dataSource: statusdatasource

            });
        }
        function dependTaskDropDownEditor(container, options) {

            $('<input id="leaddeveloper" data-text-field="DependtaskName" data-value-field="DependtaskName"  data-bind="value:' + options.field + '"/>').appendTo(container).kendoDropDownList({
                autoBind: false,
                dataValueField: "DependtaskName",
                dataTextField: "DependtaskName",
                dataSource: dependTasksdatasource
            });
            TaskID = 0;
        }

        function deleteTopicConfirmation(e, widget) {
            var grid = $('#TaskGrid').data("kendoGrid");
            deleteConfirmation(e, widget, grid);
        }

        function deleteConfirmation(e, widget, grid) {

            var currentRow = $(e.target).closest("tr"); //get the row for deletion

            var currentRowData = widget.dataItem(currentRow); //get the row data so it can be  referred later

            var kendoWindow = $("<div />").kendoWindow({

                title: "Confirmation",
                resizable: true,
                modal: true,
                width: "400px",
                deactivate: function () {
                    $('.k-window, .k-overlay').remove();
                }
            });

            kendoWindow.data("kendoWindow")

                .content($("#delete-confirmation").html())

                .center().open();

            kendoWindow

                .find(".delete-confirm,.delete-cancel")
                .click(function () {
                    if ($(this).hasClass("delete-confirm")) {

                        grid.dataSource.remove(currentRowData);

                        grid.dataSource.sync();

                    }

                    $(this).closest("[data-role=window]").kendoWindow("close");

                });

        }
        dataSource.bind("requestEnd", showSuccessMessage);
        dependTasksdatasource.bind("requestEnd", ShowDropdown);
        function ShowDropdown(e) {
        }
        function showSuccessMessage(e) {


            if (e.type === "update" || e.type === "create") {
                gridInEditMode = false;
                $("#saveConfirm").addClass('in');
                e.sender.read();
            }
        }

        $(".close").click(function () {
            $(this).parent().removeClass('in');
        });
    }
</script>

@* ...
    Show Task Subtask

*@

<script>
    function showSubTask(taskId, companyId, e) {
        HideAllUplods();
        var gridInEditMode = false;
        $('#SubTaskGrid').show();
        $('#TaskGrid tr.k-state-selected').removeClass('k-state-selected');
        var row = $(e).closest("tr");
        row.addClass("k-state-selected");
        $('#ServiceContractGrid').hide();
        $('#CompanyContactGrid').hide();
        $('#companyofficegrid').hide();
        $('#CompanyHistoryGrid').hide();
        $("#MessageGrid").hide();
        $('#SubTaskGrid').empty();

        var dataSource = new kendo.data.DataSource({
            transport: {
                read: function (options) {
                    $.ajax({
                        type: "POST",
                        url: "../AddProjectSubTask/GetSubTask",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        cache: false,
                        data: JSON.stringify({ id: taskId }),
                        success: function (data) {

                            options.success(data);
                        },
                        error: function (request, status, error) {

                            alert(request.responseText);
                        }
                    });
                },
                create: function (options) {
                    options.data.taskId = taskId

                    $.ajax({
                        type: "POST",
                        url: "/SubTask/CreateSubtask",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify(options.data),
                        success: function (data) {
                            if (data.Message) {
                                alert(data.Message);
                            }
                            options.success(data);
                        }
                    });
                },
                update: function (options) {
                    $.ajax({
                        type: "POST",
                        url: "../SubTask/UpdateSubTask",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify(options.data),

                        success: function (data) {
                            if (data.Message) {
                                alert(data.Message);
                            }
                            options.success(data);
                        }
                    });
                },
                destroy: function (options) {
                    $.ajax({
                        type: "POST",
                        url: "../SubTask/DeleteSubTask",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify({ id: options.data.id }),

                        success: function (data) {

                            options.success(data);
                        }
                    });
                },
                parameterMap: function (options) {
                    return kendo.stringify(options); // kendo.stringify serializes to JSON string
                }

            },
            schema: {
                model: {
                    id: "id",
                    fields: {
                        id: {
                            editable: false, nullable: true,
                            type: "int"
                        },
                        name: {
                            type: "string"
                        },
                        heldContactName:
                            {
                                type: "string"
                            },
                        startDate:
                            {
                                type: "date",
                                //  validation: { required: true },
                                nullable: true,
                                value: "",
                                defaultOption: null
                            },
                        endDate:
                            {
                                type: "date",
                                //  validation: { required: true },
                                nullable: true,
                                value: "",
                                defaultOption: null
                            },
                        noOfDays: {
                            type: "int",
                            validation: { required: true },
                        },

                        taskName: {
                            type: "string",
                            validation: { required: true },
                        },
                        companyId:
                            {
                                type: "string",
                                editable: false
                            },
                        gap: {
                            type: "int"
                        },

                        heldById: {
                            type: "int"
                        },

                        statusId: {
                            type: "int"
                        },
                        statusName: {
                            type: "string",
                            defaultValue: "Open"

                        },
                        notes: {
                            type: "string"

                        },

                        error: function (a) {

                            $('#SubTaskGrid').data("kendoGrid").cancelChanges();
                        },
                    }
                }
            }
        });
        var heldContactdataSource = new kendo.data.DataSource({
            transport: {
                read: function (options) {
                    $.ajax({
                        type: "GET",

                        url: "../ProductRequestGrid/GetHeldEmployee",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify({ key: "value" }),
                        success: function (data) {
                            options.success(data);
                        }
                    });
                }
            }
        });
        var statusdatasource = new kendo.data.DataSource({
            transport: {
                read: function (options) {
                    $.ajax({
                        type: "GET",

                        url: "../ScratchPad/GetStatus",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify({ key: "value" }),
                        success: function (data) {
                            options.success(data);
                        }
                    });
                }
            }
        });
        function dateTimeEditor(container, options) {
            $('<input data-text-field="' + options.field + '" data-value-field="' + options.field + '" data-bind="value:' + options.field + '" data-format="' + options.format + '"/>')
            .appendTo(container)
            .kendoDateTimePicker({});
        }

        $("#SubTaskGrid").kendoGrid({
            dataSource: dataSource,
            scrollable: true,
            height: "250px",
            toolbar: [{ name: "create", text: "Create SubTask" }, "excel"], //, "save", "cancel"],
            excel: {
                allPages: true,
                fileName: "SubTaskExport.xlsx"
            },
            pageable: true,
            height: 300,
            columns: [
          { field: "name", title: " Sub TaskName*", filterable: false, width: "6.5em" },
            {
                field: "startDate", title: "Start Date *", filterable: false, format: "{0:MM/dd/yyyy HH:mm tt}",
                editor: dateTimeEditor, width: "8em",
                filterable: {
                    ui: "datetimepicker"
                }
            },
            { field: "noOfDays", title: "Duration *", width: "8em" },

              { field: "gap", title: "Gap", width: "8em" },
                 { field: "heldContactName", title: "Held By*", editor: heldEmployeeDropDownEditor, width: "8em" },
                 {
                     field: "endDate", title: "End Date", editable: true, filterable: false, format: "{0:MM/dd/yyyy HH:mm tt}",
                     editor: dateTimeEditor, width: "8em",
                     filterable: {
                         ui: "datetimepicker"
                     }
                 },
                    {
                        field: "notes", title: "Notes", width: "200px", editor: function (container, options) {
                            $('<textarea data-bind="value: ' + options.field + '" cols="20" rows="10"></textarea>').appendTo(container);
                        }
                    },
                     { field: "companyId", hidden: true, editable: false, width: "8em" },
                     { field: "statusName", title: "Status*", editor: statusDropDownEditor, width: "8em" },
          {
              title: "&nbsp;",
              width: "25em",

              command: [
                  "edit",
                  {
                      name: "Delete",
                      click: function (e) {

                          var tr = $(e.target).closest("tr"); //get the row for deletion
                          var dataItem = this.dataItem(tr); //get the row data so it can be referred later
                          //see what is coming in dataItem
                          //if (dataItem > 0) {
                          //    $("#delValidation").addClass('in')
                          //}
                          //else {

                          deleteTopicConfirmation(e, this);
                          ////}
                          return false;
                      }
                  }
              ]
          }
            ],
            filterable: {
                extra: false,
                operators: {
                    string: {
                        eq: "Is equal to",
                        neq: "Is not equal to",
                        contains: "Contains"
                    }
                }
            },

            editable: "popup",
            sortable: {
                mode: "single",
                allowUnsort: false
            },
            edit: function (e) {
                e.container.find(".k-edit-label:nth-child(15)").hide();
                e.container.find(".k-edit-field:nth-child(16)").hide();
                gridInEditMode = true;
            },
            excelExport: function (e) {
                for (var i = 0; i < e.workbook.sheets[0].columns.length; i++) {
                    e.workbook.sheets[0].columns[i].autoWidth = true;
                }
            },
            selectable: true,
            cancel: function (e) {
                gridInEditMode = false;
            }
        });
        $("#SubTaskGrid").kendoTooltip({
            filter: "td:nth-child(7)", //this filter selects the second column's cells
            position: "left",
            content: function (e) {
                var target = e.target;
                return $(target).text();

            }
        }).data("kendoTooltip");


        function heldEmployeeDropDownEditor(container, options) {
            $('<input id="ManagerId" data-text-field="heldContactName" data-value-field="heldById"  data-bind="value:' + options.field + '"/>').appendTo(container).kendoDropDownList({
                autoBind: false,
                dataValueField: "heldById",
                dataTextField: "heldContactName",
                dataSource: heldContactdataSource

            });
        }
        function statusDropDownEditor(container, options) {
            $('<input id="leaddeveloper" data-text-field="statusName" data-value-field="statusName"  data-bind="value:' + options.field + '"/>').appendTo(container).kendoDropDownList({
                autoBind: false,
                dataValueField: "statusName",
                dataTextField: "statusName",
                dataSource: statusdatasource

            });
        }
        dataSource.bind("requestEnd", showSuccessMessage);
        function showSuccessMessage(e) {
            if (e.type === "update" || e.type === "create") {
                gridInEditMode = false;
                $("#saveConfirm").addClass('in');
                e.sender.read();
            }
        }
        $(".close").click(function () {
            $(this).parent().removeClass('in');
        });

        function deleteTopicConfirmation(e, widget) {
            var grid = $('#SubTaskGrid').data("kendoGrid");
            deleteConfirmation(e, widget, grid);
        }

        function deleteConfirmation(e, widget, grid) {

            var currentRow = $(e.target).closest("tr"); //get the row for deletion

            var currentRowData = widget.dataItem(currentRow); //get the row data so it can be  referred later

            var kendoWindow = $("<div />").kendoWindow({

                title: "Confirmation",
                resizable: true,
                modal: true,
                width: "400px",
                deactivate: function () {
                    $('.k-window, .k-overlay').remove();
                }
            });

            kendoWindow.data("kendoWindow")

                .content($("#delete-confirmation").html())

                .center().open();

            kendoWindow

                .find(".delete-confirm,.delete-cancel")
                .click(function () {
                    if ($(this).hasClass("delete-confirm")) {

                        grid.dataSource.remove(currentRowData);

                        grid.dataSource.sync();

                    }

                    $(this).closest("[data-role=window]").kendoWindow("close");

                });

        }
    }
</script>

@* ...
    Show Task History

*@

<script>
    function showTaskHistory(taskId, e) {
        HideAllUplods();
        var gridInEditMode = false;
        $('#TaskHistoryGrid').show();
        $('#TaskGrid tr.k-state-selected').removeClass('k-state-selected');
        var row = $(e).closest("tr");
        row.addClass("k-state-selected");

        $('#SubTaskGrid').hide();
        $('#ServiceContractGrid').hide();
        $('#CompanyContactGrid').hide();
        $('#companyofficegrid').hide();
        $('#CompanyHistoryGrid').hide();
        $("#MessageGrid").hide();
        $('#TaskHistoryGrid').empty();

        var TaskHistorydataSource = new kendo.data.DataSource({
            transport: {
                read: function (options) {
                    $.ajax({
                        type: "POST",
                        url: "../Task/GetTaskHistory",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        cache: false,
                        data: JSON.stringify({ id: taskId }),
                        success: function (data) {

                            options.success(data);
                        },
                        error: function (request, status, error) {

                            alert(request.responseText);
                        }
                    });
                },
                destroy: function (options) {
                    $.ajax({
                        type: "POST",
                        url: "../CompanyHistory/DeleteHistory",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify({ id: options.data.id }),

                        success: function (data) {

                            options.success(data);
                        }
                    });
                },
                parameterMap: function (options) {
                    return kendo.stringify(options); // kendo.stringify serializes to JSON string
                }
            },
            schema: {
                model: {
                    id: "id",
                    fields: {
                        id: {
                            editable: false, nullable: true,
                            type: "int"
                        },
                        name: {
                            type: "string"
                        },
                        HeldName:
                            {
                                type: "string"
                            },
                        startDate:
                            {
                                type: "date",
                                //  validation: { required: true },
                                nullable: true,
                                value: "",
                                defaultOption: null
                            },
                        endDate:
                            {
                                type: "date",
                                //  validation: { required: true },
                                nullable: true,
                                value: "",
                                defaultOption: null
                            },

                        dateChanged:
                            {
                                type: "date",
                                //  validation: { required: true },
                                nullable: true,
                                value: "",
                                defaultOption: null
                            },
                        taskId: {
                            type: "int"
                        },
                        heldBy: {
                            type: "int"
                        },

                        status: {
                            type: "int"
                        },
                        statusName: {
                            type: "string"
                        },
                        notes: {
                            type: "string",
                            // validation: { required: true }
                        },

                        error: function (a) {

                            $('#TaskHistoryGrid').data("kendoGrid").cancelChanges();
                        },
                    }
                }
            }
        });
        function dateTimeEditor(container, options) {
            $('<input data-text-field="' + options.field + '" data-value-field="' + options.field + '" data-bind="value:' + options.field + '" data-format="' + options.format + '"/>')
            .appendTo(container)
            .kendoDateTimePicker({});
        }

        $("#TaskHistoryGrid").kendoGrid({
            dataSource: TaskHistorydataSource,
            scrollable: true,
            height: "250px",
            toolbar: [{ name: "create", text: "Just To show History" }, "excel"], //, "save", "cancel"],
            excel: {
                allPages: true,
                fileName: "TaskHistoryExport.xlsx"
            },
            pageable: true,
            height: 300,
            columns: [
          { field: "name", title: "TaskName", filterable: false, width: "8em" },
            {
                field: "startDate", title: "Start Date", filterable: false, format: "{0:MM/dd/yyyy HH:mm tt}",
                editor: dateTimeEditor,
                filterable: {
                    ui: "datetimepicker"
                }
            },
            {
                field: "endDate", title: "End Date", filterable: false, format: "{0:MM/dd/yyyy HH:mm tt}",
                editor: dateTimeEditor,
                filterable: {
                    ui: "datetimepicker"
                }
            },
      {
          field: "dateChanged", title: "Date Changed", filterable: false, format: "{0:MM/dd/yyyy HH:mm tt}",
          editor: dateTimeEditor,
          filterable: {
              ui: "datetimepicker"
          }
      },

              { field: "description", title: "Description", width: "8em" },
                 { field: "HeldName", title: "Held By", width: "8em" },

                 {
                     field: "endDate", title: "End Date", hidden: true, editable: true, filterable: false, format: "{0:MM/dd/yyyy HH:mm tt}",
                     editor: dateTimeEditor,
                     filterable: {
                         ui: "datetimepicker"
                     }
                 },
                  {
                      field: "dateChanged", title: "Change Date", hidden: true, editable: true, filterable: false, format: "{0:MM/dd/yyyy HH:mm tt}",
                      editor: dateTimeEditor,
                      filterable: {
                          ui: "datetimepicker"
                      }
                  },
                    {
                        field: "notes", title: "Notes", width: "200px", editor: function (container, options) {
                            $('<textarea data-bind="value: ' + options.field + '" cols="20" rows="10"></textarea>').appendTo(container);
                        }
                    },
                     { field: "statusName", title: "Status", width: "8em" },
          {
              title: "&nbsp;",
              width: "25em",

              command: [
                  "edit",
                  {
                      name: "Delete",
                      click: function (e) {

                          var tr = $(e.target).closest("tr"); //get the row for deletion
                          var dataItem = this.dataItem(tr); //get the row data so it can be referred later
                          //see what is coming in dataItem
                          //if (dataItem > 0) {
                          //    $("#delValidation").addClass('in')
                          //}
                          //else {

                          deleteTopicConfirmation(e, this);
                          ////}
                          return false;
                      }
                  }
              ]
          }
            ],
            filterable: {
                extra: false,
                operators: {
                    string: {
                        eq: "Is equal to",
                        neq: "Is not equal to",
                        contains: "Contains"
                    }
                }
            },

            editable: "popup",
            sortable: {
                mode: "single",
                allowUnsort: false
            },
            selectable: true,
            excelExport: function (e) {
                for (var i = 0; i < e.workbook.sheets[0].columns.length; i++) {
                    e.workbook.sheets[0].columns[i].autoWidth = true;
                }
            },
            cancel: function () {
                gridInEditMode = false;
            }
        });
        TaskHistorydataSource.bind("requestEnd", showSuccessMessage);
        function showSuccessMessage(e) {
            if (e.type === "update" || e.type === "create") {
                gridInEditMode = false;
                e.sender.read();
            }
        }
        $(".close").click(function () {
            $(this).parent().removeClass('in');
        });

    }
</script>

@* ...
    Show Company Offices

*@

<script type="text/javascript">

    function showCompanyOffices(companyId, e) {
        HideAllUplods();
        var gridInEditMode = false;
        $('#addcompanyGrid tr.k-state-selected').removeClass('k-state-selected');
        var row = $(e).closest("tr");
        row.addClass("k-state-selected");

        $('#companyofficegrid').show();
        $('#SubTaskGrid').hide();
        $('#ServiceContractGrid').hide();
        $('#CompanyContactGrid').hide();
        $('#ProductRequestGrid').hide();
        $('#CompanyHistoryGrid').hide();
        $("#MessageGrid").hide();
        $('#companyofficegrid').empty();
        var dataSource = new kendo.data.DataSource({
            transport: {

                read: function (options) {
                    $.ajax({
                        type: "POST",
                        url: "/CompanyOffice/GetCompanyOffice",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        cache: false,
                        data: JSON.stringify({ id: companyId }),
                        success: function (data) {
                            options.success(data);
                        }
                    });
                },

                create: function (options) {
                    debugger;
                    options.data.companyId = companyId;

                    var CompanyOfficeViewModel = new Object();
                    CompanyOfficeViewModel.id = options.data.id;
                    CompanyOfficeViewModel.companyId = options.data.companyId;


                    if (options.data.stateId)
                        CompanyOfficeViewModel.stateId = options.data.stateId.id;
                    CompanyOfficeViewModel.city = options.data.city;
                    CompanyOfficeViewModel.phone = options.data.phone;
                    CompanyOfficeViewModel.faxNumber = options.data.faxNumber;
                    CompanyOfficeViewModel.notes = options.data.notes;
                    CompanyOfficeViewModel.address = options.data.address;
                    CompanyOfficeViewModel.zip = options.data.zip;
                    CompanyOfficeViewModel.timeZone = options.data.timeZone;
                    CompanyOfficeViewModel.dateStart = options.data.dateStart;
                    CompanyOfficeViewModel.dateEnd = options.data.dateEnd;
                    CompanyOfficeViewModel.country = options.data.country;
                    CompanyOfficeViewModel.description = options.data.description;
                    CompanyOfficeViewModel.name = options.data.name;



                    $.ajax({
                        type: "POST",
                        url: "/CompanyOffice/CreateCompanyOffice",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify(CompanyOfficeViewModel),

                        success: function (data) {
                            if (data.Message) {
                                alert(data.Message);
                            }
                            options.success(data);
                        }
                    });
                },
                update: function (options) {
                    debugger;
                    var CompanyOfficeViewModel = new Object();
                    CompanyOfficeViewModel.id = options.data.id;
                    CompanyOfficeViewModel.companyId = options.data.companyId;
                    CompanyOfficeViewModel.state = options.data.state;
                    CompanyOfficeViewModel.city = options.data.city;
                    CompanyOfficeViewModel.phone = options.data.phone;
                    CompanyOfficeViewModel.faxNumber = options.data.faxNumber;
                    CompanyOfficeViewModel.notes = options.data.notes;
                    CompanyOfficeViewModel.address = options.data.address;
                    CompanyOfficeViewModel.zip = options.data.zip;
                    CompanyOfficeViewModel.timeZone = options.data.timeZone;
                    CompanyOfficeViewModel.dateStart = options.data.dateStart;
                    CompanyOfficeViewModel.dateEnd = options.data.dateEnd;
                    CompanyOfficeViewModel.country = options.data.country;
                    CompanyOfficeViewModel.description = options.data.description;
                    CompanyOfficeViewModel.name = options.data.name;

                    $.ajax({
                        type: "POST",
                        url: "../CompanyOffice/UpdateCompanyOffice",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify(CompanyOfficeViewModel),

                        success: function (data) {
                            if (data.Message) {
                                alert(data.Message);
                            }
                            options.success(data);
                        }
                    });
                },

                destroy: function (options) {
                    $.ajax({
                        type: "POST",
                        url: "/CompanyOffice/DeleteCompanyOffice",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify({ id: options.data.id }),

                        success: function (data) {

                            options.success(data);
                        }
                    });
                },
                parameterMap: function (options) {
                    return kendo.stringify(options); // kendo.stringify serializes to JSON string
                },
            },
            schema: {
                model: {
                    id: "id",
                    fields: {
                        id: {
                            editable: false, nullable: true,
                            type: "int"
                        },
                        name: {
                            type: "string",
                            validation: { required: true }
                        },

                        stateName: {
                            type: "string",
                            validation: { required: true }
                        },
                        description: {

                            type: "string",

                        },
                        phone:
                            {
                                type: "string",

                            },
                        faxNumber:
                           {
                               type: "string",

                           },
                        notes:
                           {
                               type: "string",

                           },
                        address:
                           {
                               type: "string",

                           },
                        zip:
                           {
                               type: "string",

                           },
                        country:
                           {
                               type: "string",

                           },
                        timeZone:
                           {
                               type: "string",

                           },
                        dateStart:
                               {
                                   type: "date",
                                   //  validation: { required: true },
                                   nullable: true,
                                   value: "",
                                   defaultOption: null
                               },

                        dateEnd:
                           {
                               type: "date",
                               //  validation: { required: true },
                               nullable: true,
                               value: "",
                               defaultOption: null
                           },
                        error: function (a) {
                            $('#companyofficegrid').data("kendoGrid").cancelChanges();
                        },

                    }
                }
            }

        });
        var statesdataSource = new kendo.data.DataSource({
            transport: {
                read: function (options) {
                    $.ajax({
                        type: "GET",
                        url: "/AddCompany/GetStates",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify({ key: "value" }),
                        success: function (data) {
                            options.success(data);
                        }
                    });
                }
            }
        });

        function dateTimeEditor(container, options) {
            $('<input data-text-field="' + options.field + '" data-value-field="' + options.field + '" data-bind="value:' + options.field + '" data-format="' + options.format + '"/>')
            .appendTo(container)
            .kendoDateTimePicker({});
        }
        $("#companyofficegrid").kendoGrid({
            dataSource: dataSource,
            scrollable: true,
            height: "250px",
            toolbar: [{ name: "create", text: "Create CompanyOffice" }, "excel"], //, "save", "cancel"],
            excel: {
                allPages: true,
                fileName: "CompanyOfficeExport.xlsx"
            },
            pageable: true,
            height: 300,
            columns: [

          { field: "name", title: "Name *", filterable: false, width: "8em" },
             { field: "description", title: "Description", filterable: false, width: "8em" },

          { field: "phone", title: "Phone", width: "8em" },
            { field: "faxNumber", title: "Fax", width: "8em" },
              { field: "address", title: "Address", width: "8em" },
                { field: "city", title: "City", width: "8em" },
                  { field: "stateName", title: "State *", editor: stateDropDownEditor, width: "8em" },
                { field: "zip", title: "Zip", width: "8em" },
                  { field: "country", title: "Country", editor: countryDropDownEditor, width: "8em" },
                   { field: "timeZone", title: "Time Zone", editor: timeZoneDropDownEditor, width: "8em" },
                    {
                        field: "notes", title: "Notes", width: "200px", editor: function (container, options) {
                            $('<textarea data-bind="value: ' + options.field + '" cols="20" rows="10"></textarea>').appendTo(container);
                        }
                    },
           {

               field: "dateStart", title: "Start Date", hidden: true, filterable: false, format: "{0:MM/dd/yyyy HH:mm tt}",
               editor: dateTimeEditor,
               filterable: {
                   ui: "datetimepicker"
               }
           },

                 {
                     field: "dateEnd", title: "End Date", hidden: true, editable: true, filterable: false, format: "{0:MM/dd/yyyy HH:mm tt}",
                     editor: dateTimeEditor,
                     filterable: {
                         ui: "datetimepicker"
                     }
                 },


          {
              title: "&nbsp;",
              width: "25em",
              //command: ["edit", "destroy"]
              command: [

                  "edit",
                  {
                      name: "Delete",


                      click: function (e) {
                          var tr = $(e.target).closest("tr"); //get the row for deletion
                          var dataItem = this.dataItem(tr); //get the row data so it can be referred later
                          //see what is coming in dataItem
                          //if (dataItem > 0) {
                          //    $("#delValidation").addClass('in')
                          //}
                          //else {

                          deleteTopicConfirmation(e, this);
                          ////}
                          return false;
                      }
                  }
              ]
          }
            ],
            filterable: {
                extra: false,
                operators: {
                    string: {
                        eq: "Is equal to",
                        neq: "Is not equal to",
                        contains: "Contains"
                    }
                }
            },

            editable: "popup",
            sortable: {
                mode: "single",
                allowUnsort: false
            },
            excelExport: function (e) {
                for (var i = 0; i < e.workbook.sheets[0].columns.length; i++) {
                    e.workbook.sheets[0].columns[i].autoWidth = true;
                }
            },
            selectable: true,
            // change: onTopicChange,
            // dataBound: onTopicsGridDataBound,

            cancel: function () {
                gridInEditMode = false;
            }
        });
        $("#companyofficegrid").kendoTooltip({
            filter: "td:nth-child(11)", //this filter selects the second column's cells
            position: "left",
            content: function (e) {
                var target = e.target;
                return $(target).text();

            }
        }).data("kendoTooltip");



        function stateDropDownEditor(container, options) {

            $('<input required="required" name="State" data-text-field="stateName" data-value-field="id" data-bind="value:stateId"/>').appendTo(container).kendoDropDownList({
                autoBind: true,
                dataValueField: "id",
                dataTextField: "stateName",
                dataSource: statesdataSource
            });
            $('<span class="k-invalid-msg" data-for="State"></span>').appendTo(container);
        }
        function countryDropDownEditor(container, options) {
            $('<input id="countryId" data-text-field="dataText" data-value-field="dataText"  data-bind="value:' + options.field + '"/>').appendTo(container).kendoDropDownList({
                autoBind: true,
                dataSource: { data: [{ dataText: "USA", dataValue: "1" }, { dataText: "CANADA", dataValue: "2" }, { dataText: "FRANCE", dataValue: "3" }, { dataText: "ITALY", dataValue: "4" }, { dataText: "ENGLAND", dataValue: "5" }] }

            });
        }
        function timeZoneDropDownEditor(container, options) {
            $('<input id="timeZoneId" data-text-field="dataText" data-value-field="dataText"  data-bind="value:' + options.field + '"/>').appendTo(container).kendoDropDownList({
                autoBind: true,
                dataSource: { data: [{ dataText: "ET", dataValue: "1" }, { dataText: "CT", dataValue: "2" }, { dataText: "PT", dataValue: "3" }, { dataText: "KT", dataValue: "4" }] }

            });
        }
        dataSource.bind("requestEnd", showSuccessMessage);
        function showSuccessMessage(e) {
            if (e.type === "update" || e.type === "create") {
                gridInEditMode = false;
                $("#saveConfirm").addClass('in');
                e.sender.read();
            }
        }
        $(".close").click(function () {
            $(this).parent().removeClass('in');
        });
        function deleteTopicConfirmation(e, widget) {
            var grid = $('#companyofficegrid').data("kendoGrid");
            deleteConfirmation(e, widget, grid);
        }

        function deleteConfirmation(e, widget, grid) {

            var currentRow = $(e.target).closest("tr"); //get the row for deletion

            var currentRowData = widget.dataItem(currentRow); //get the row data so it can be  referred later

            var kendoWindow = $("<div />").kendoWindow({

                title: "Confirmation",
                resizable: true,
                modal: true,
                width: "400px",
                deactivate: function () {
                    $('.k-window, .k-overlay').remove();
                }
            });

            kendoWindow.data("kendoWindow")

                .content($("#delete-confirmation").html())

                .center().open();

            kendoWindow

                .find(".delete-confirm,.delete-cancel")
                .click(function () {
                    if ($(this).hasClass("delete-confirm")) {
                        grid.dataSource.remove(currentRowData);
                        grid.dataSource.sync();
                    }
                    $(this).closest("[data-role=window]").kendoWindow("close");

                });
        }
    }

</script>

@* ...
    Show Company History

*@

<script type="text/javascript">

    function showCompanyHistory(companyId, e) {
        HideAllUplods();
        $('#addcompanyGrid tr.k-state-selected').removeClass('k-state-selected');
        var row = $(e).closest("tr");
        row.addClass("k-state-selected");
        $('#CompanyHistoryGrid').show();
        $('#companyofficegrid').hide();
        $('#SubTaskGrid').hide();
        $('#ServiceContractGrid').hide();
        $('#CompanyContactGrid').hide();
        $('#ProductRequestGrid').hide();
        $('#TaskGrid').hide();
        $("#MessageGrid").hide();
        var dataSource = new kendo.data.DataSource({
            transport: {
                read: function (options) {
                    $.ajax({
                        type: "POST",
                        url: "../CompanyHistory/GetCompanyHistory",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify({ id: companyId }),

                        success: function (data) {

                            options.success(data);
                        },

                        error: function (request, status, error) {

                            alert(request.responseText);
                        }
                    });
                },
                destroy: function (options) {
                    $.ajax({
                        type: "POST",
                        url: "../CompanyHistory/DeleteHistory",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify({ id: companyId }),

                        success: function (data) {

                            options.success(data);
                        }
                    });
                },
                parameterMap: function (options) {
                    return kendo.stringify(options); // kendo.stringify serializes to JSON string
                },

            },
            schema: {
                model: {
                    id: "id",
                    fields: {
                        id: {
                            editable: false, nullable: true,
                            type: "int"
                        },
                        companyId: {
                            type: "int"
                        },
                        name:
                            {
                                type: "string"
                            },
                        phone:
                            {

                                type: "string"
                            },
                        fax:
                    {
                        type: "string"
                    },
                        companyTypeId:
                   {
                       type: "int"
                   },
                        clientTypeId:
              {
                  type: "int"
              },
                        relationStart:
              {
                  type: "date",
                  //  validation: { required: true },
                  nullable: true,
                  value: "",
                  defaultOption: null
              },
                        relationEnd: {
                            type: "date",
                            //  validation: { required: true },
                            nullable: true,
                            value: "",
                            defaultOption: null
                        },

                        error: function (a) {

                            $('#CompanyHistoryGrid').data("kendoGrid").cancelChanges();
                        },

                    }
                }
            }

        });

        function dateTimeEditor(container, options) {
            $('<input data-text-field="' + options.field + '" data-value-field="' + options.field + '" data-bind="value:' + options.field + '" data-format="' + options.format + '"/>')
            .appendTo(container)
            .kendoDateTimePicker({});
        }

        $("#CompanyHistoryGrid").kendoGrid({
            dataSource: dataSource,
            scrollable: true,
            height: "250px",
            toolbar: [{ name: "create", text: "Show Company History" }, "excel"], //, "save", "cancel"],
            excel: {
                fileName: "CompanyHistoryExport.xlsx"
            },
            pageable: true,
            height: 300,
            columns: [
         // { field: "LogsDate", title: "LogsDate*", filterable: false },
          { field: "name", title: "Name", filterable: false, width: "8em" },
          { field: "phone", title: "Phone", width: "8em" },
            { field: "fax", title: "Fax", width: "8em" },
              { field: "clientType", title: "ClientType", width: "8em" },
                { field: "companyType", title: "CompanyType", width: "8em" },
           {
               field: "relationStart", title: "Start Date", hidden: true, filterable: false, format: "{0:MM/dd/yyyy HH:mm tt}",
               editor: dateTimeEditor,
               filterable: {
                   ui: "datetimepicker"
               }
           },

                 {
                     field: "relationEnd", title: "End Date", hidden: true, editable: true, filterable: false, format: "{0:MM/dd/yyyy HH:mm tt}",
                     editor: dateTimeEditor,
                     filterable: {
                         ui: "datetimepicker"
                     }
                 },

                 {
                     field: "updateDate", title: "Update Date", hidden: true, editable: true, filterable: false, format: "{0:MM/dd/yyyy HH:mm tt}",
                     editor: dateTimeEditor, width: "8em",
                     filterable: {
                         ui: "datetimepicker"
                     }
                 },

          {
              title: "&nbsp;",
              width: "25em",
              //command: ["edit", "destroy"]
              command: [

                  "edit",
                  {
                      name: "Delete",


                      click: function (e) {

                          var tr = $(e.target).closest("tr"); //get the row for deletion
                          var dataItem = this.dataItem(tr); //get the row data so it can be referred later
                          //see what is coming in dataItem
                          //if (dataItem > 0) {
                          //    $("#delValidation").addClass('in')
                          //}
                          //else {

                          deleteTopicConfirmation(e, this);
                          ////}
                          return false;
                      }
                  }
              ]
          }
            ],
            filterable: {
                extra: false,
                operators: {
                    string: {
                        eq: "Is equal to",
                        neq: "Is not equal to",
                        contains: "Contains"
                    }
                }
            },

            editable: "popup",
            sortable: {
                mode: "single",
                allowUnsort: false
            },
            selectable: true,
            // change: onTopicChange,
            // dataBound: onTopicsGridDataBound,

            cancel: function () {
                JobGrid.gridInEditMode = false;
            }
        });
        function deleteTopicConfirmation(e, widget) {
            var grid = $('#CompanyHistoryGrid').data("kendoGrid");
            deleteConfirmation(e, widget, grid);
        }

        function deleteConfirmation(e, widget, grid) {

            var currentRow = $(e.target).closest("tr"); //get the row for deletion

            var currentRowData = widget.dataItem(currentRow); //get the row data so it can be  referred later

            var kendoWindow = $("<div />").kendoWindow({

                title: "Confirmation",
                resizable: true,
                modal: true,
                width: "400px",
                deactivate: function () {
                    $('.k-window, .k-overlay').remove();
                }
            });

            kendoWindow.data("kendoWindow")

                .content($("#delete-confirmation").html())

                .center().open();

            kendoWindow

                .find(".delete-confirm,.delete-cancel")
                .click(function () {
                    if ($(this).hasClass("delete-confirm")) {

                        grid.dataSource.remove(currentRowData);

                        grid.dataSource.sync();

                    }

                    $(this).closest("[data-role=window]").kendoWindow("close");

                });

        }
        dataSource.bind("requestEnd", showSuccessMessage);
        function showSuccessMessage(e) {
            if (e.type === "update" || e.type === "create") {
                gridInEditMode = false;
                $("#saveConfirm").addClass('in');
                e.sender.read();
            }
        }
        $(".close").click(function () {
            $(this).parent().removeClass('in');
        });
    }

</script>

@* ...
    Show Company messages

*@

<script type="text/javascript">

    var IsAssEmpChecked = false, IsAllContChecked = false, IsCompContChecked = false, allContactIdsVar = null, companyContactIdsVar = null, assignedEmployeeIdVar = null;

    var editedUID = "";

    function UpdateIdinIsAssEmp(e) {
        IsAssEmpChecked = true;
    }
    function UpdateIdinIsAllCont(e) {
        IsAllContChecked = true;
    }
    function UpdateIdinIsCompCont(e) {
        IsCompContChecked = true;
    }
    function showCompanyMessages(companyId, e) {
        HideAllUplods();
        $('#addcompanyGrid tr.k-state-selected').removeClass('k-state-selected');
        var row = $(e).closest("tr");
        row.addClass("k-state-selected");
        var gridInEditMode = false;

        $("#MessageGrid").show();
        $('#companyofficegrid').hide();
        $('#SubTaskGrid').hide();
        $('#ServiceContractGrid').hide();
        $('#CompanyContactGrid').hide();
        $('#ProductRequestGrid').hide();
        $('#CompanyHistoryGrid').hide();
        $('#SalesLeadGrid').hide();
        $("#MessageGrid").empty();
        var dataSource = new kendo.data.DataSource({
            transport: {
                read: function (options) {
                    $.ajax({
                        type: "POST",
                        url: "../CommunicationMessageGrid/GetCommunicationMessages",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        cache: false,
                        async: false,
                        data: JSON.stringify({ id: companyId }),
                        success: function (data) {

                            options.success(data);
                        },
                        error: function (request, status, error) {

                            alert(request.responseText);
                        }
                    });
                },
                create: function (options) {
                    debugger;
                    options.data.companyId = companyId;
                    var CompanyCommunicationViewModel = new Object();
                    CompanyCommunicationViewModel.id = options.data.id;
                    CompanyCommunicationViewModel.userID = options.data.userID;
                    CompanyCommunicationViewModel.companyId = options.data.companyId;
                    if (options.data.communicationTypeID)
                        CompanyCommunicationViewModel.communicationTypeID = options.data.communicationTypeID.id;
                    CompanyCommunicationViewModel.subject = options.data.subject;
                    if (options.data.productID)
                        CompanyCommunicationViewModel.productID = options.data.productID.id;
                    CompanyCommunicationViewModel.notes = options.data.notes;
                    CompanyCommunicationViewModel.followUpdate = options.data.followUpdate;
                    if (options.data.statusID)
                        CompanyCommunicationViewModel.statusID = options.data.statusID.status;
                    if (options.data.officeId)
                        CompanyCommunicationViewModel.officeId = options.data.officeId.officeId;
                    CompanyCommunicationViewModel.emailTo = options.data.emailTo;
                    CompanyCommunicationViewModel.phone = options.data.phone;
                    CompanyCommunicationViewModel.assignedEmployeeID = options.data.assignedEmployeeID;
                    CompanyCommunicationViewModel.communicationDate = options.data.communicationDate;
                    CompanyCommunicationViewModel.AllContactIds = options.data.AllContactIds;
                    CompanyCommunicationViewModel.CompanyContactIds = options.data.CompanyContactIds;
                    CompanyCommunicationViewModel.CommEmployeeIds = options.data.CommEmployeeIds;
                    CompanyCommunicationViewModel.logInOwner = options.data.logInOwner;
                    CompanyCommunicationViewModel.inOrOut = options.data.inOrOut;


                    $.ajax({
                        type: "POST",
                        url: "../CommunicationMessageGrid/CreateCompanyMessages",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify(CompanyCommunicationViewModel),

                        success: function (data) {
                            if (data.Message) {
                                alert(data.Message);
                            }
                            options.success(data);
                        }
                    });
                },
                update: function (options) {
                    debugger;
                    options.data.companyId = companyId;
                    var CompanyCommunicationViewModel = new Object();
                    CompanyCommunicationViewModel.id = options.data.id;
                    CompanyCommunicationViewModel.userID = options.data.userID;
                    CompanyCommunicationViewModel.companyId = options.data.companyId;
                    CompanyCommunicationViewModel.communicationTypeID = options.data.communicationTypeID;
                    CompanyCommunicationViewModel.subject = options.data.subject;
                    CompanyCommunicationViewModel.productID = options.data.productID;
                    CompanyCommunicationViewModel.notes = options.data.notes;
                    CompanyCommunicationViewModel.followUpdate = options.data.followUpdate;
                    CompanyCommunicationViewModel.statusID = options.data.statusID;
                    CompanyCommunicationViewModel.officeId = options.data.officeId;
                    CompanyCommunicationViewModel.emailTo = options.data.emailTo;
                    CompanyCommunicationViewModel.phone = options.data.phone;
                    CompanyCommunicationViewModel.assignedEmployeeID = options.data.assignedEmployeeID;
                    CompanyCommunicationViewModel.communicationDate = options.data.communicationDate;
                    CompanyCommunicationViewModel.AllContactIds = options.data.AllContactIds;
                    CompanyCommunicationViewModel.CompanyContactIds = options.data.CompanyContactIds;
                    CompanyCommunicationViewModel.CommEmployeeIds = options.data.CommEmployeeIds;
                    CompanyCommunicationViewModel.logInOwner = options.data.logInOwner;
                    CompanyCommunicationViewModel.inOrOut = options.data.inOrOut;


                    $.ajax({
                        type: "POST",
                        url: "../CommunicationMessageGrid/UpdateCompanyMessages",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify(CompanyCommunicationViewModel),

                        success: function (data) {
                            if (data.Message) {
                                alert(data.Message);
                            }
                            options.success(data);
                        }
                    });
                },

                destroy: function (options) {
                    $.ajax({
                        type: "POST",
                        url: "../CommunicationMessageGrid/DeleteCompanyMessages",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        async: false,
                        data: JSON.stringify({ id: options.data.id }),

                        success: function (data) {

                            options.success(data);
                        }
                    });
                },
                parameterMap: function (options) {
                    return kendo.stringify(options); // kendo.stringify serializes to JSON string
                }
            },
            schema: {
                model: {
                    id: "id",
                    fields: {
                        id: {
                            editable: false, nullable: true,
                            type: "int"
                        },
                        //followUpdate: { type: "date", parse: function (value) { return new Date(value); } },
                        followUpdate: {
                            type: "date",
                            //  validation: { required: true },
                            nullable: true,
                            value: "",
                            defaultOption: null

                        },
                        communicationDate: {
                            type: "date",
                            //  validation: { required: true },
                            nullable: true,
                            value: "",
                            defaultOption: null

                        },
                        logInOwner:
                           {
                               defaultValue: "@User.Identity.Name",
                               type: "string"
                           },
                        note: {
                            type: "string"
                        },
                        feedback:
                        {
                            editable: false,
                            type: "string",
                            encoded: false

                        },
                        FeedbackNote:
                          {
                              editable: false,
                              type: "string",
                              encoded: false

                          },
                        contactID: {
                            type: "string"
                        },
                        companyoffice: {
                            type: "string",
                            defaultValue: "None"

                        },
                        product: {
                            type: "string",
                            validation: { required: true }
                        },

                        commVia: {
                            type: "string",
                            validation: { required: true }
                        },
                        contactname:
                             {
                                 type: "string"
                             },
                        InvoluedEname:
                           {
                               type: "string"
                           },

                        assignedEmployeeID: {
                            type: "string"
                        },
                        CompanyContactIds: {
                            type: "string",
                        },
                        email: {
                            type: "string",
                            validation: { required: true }
                        },
                        emailTo: {
                            type: "string",

                        },

                        phone: {
                            type: "string"
                        },

                        statusName: {
                            type: "string",
                            validation: { required: true }
                        },

                        subject: {
                            type: "string"
                        },

                        notes: {

                            type: "string",

                        },
                        officeId:
                        {
                            type: "int"
                           
                        },
                        name:
                            {
                                type: "string"
                            },

                        createdDate: {
                            type: "date"

                        },

                        inOrOut: {
                            type: "string",
                            defaultValue: "In",
                        },

                        error: function (a) {
                            $('#MessageGrid').data("kendoGrid").cancelChanges();
                        },

                    }
                }
            }
        });
        var productdatasource = new kendo.data.DataSource({
            transport: {
                read: function (options) {
                    $.ajax({
                        type: "GET",
                        url: "../ScratchPad/GetAllProducts",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify({ key: "value" }),
                        success: function (data) {
                            options.success(data);
                        }
                    });
                }
            }
        });
        var statusdatasource = new kendo.data.DataSource({
            transport: {
                read: function (options) {
                    $.ajax({
                        type: "GET",

                        url: "../ScratchPad/GetStatus",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify({ key: "value" }),
                        success: function (data) {
                            options.success(data);
                        }
                    });
                }
            }
        });
        var contactedviadatasource = new kendo.data.DataSource({
            transport: {
                read: function (options) {
                    $.ajax({
                        type: "GET",

                        url: "../ScratchPad/GetAllCommunicationMedium",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify({ key: "value" }),
                        success: function (data) {
                            options.success(data);
                        }
                    });
                }
            }
        });
        var officedatasource = new kendo.data.DataSource({
            transport: {
                read: function (options) {
                    $.ajax({
                        type: "POST",

                        url: "../CompanyOffice/GetCompanyOfficeByCompanyId",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify({ id: companyId }),
                        success: function (data) {
                            options.success(data);
                        }
                    });
                }
            },
        });
        var companycontactsdatasource = new kendo.data.DataSource({
            transport: {
                read: function (options) {
                    $.ajax({
                        type: "POST",

                        url: "../CommunicationMessageGrid/GetAllCompanyContacts",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify({ id: companyId }),
                        success: function (data) {
                            options.success(data);
                        }
                    });
                }
            }
        });
        var allcontactsdatasource = new kendo.data.DataSource({
            transport: {
                read: function (options) {
                    $.ajax({
                        type: "GET",
                        url: "../CommunicationMessageGrid/GetAllContacts",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        success: function (data) {
                            options.success(data);
                        }
                    });
                }
            }
        });
        var involuedEmployees = new kendo.data.DataSource({
            transport: {
                read: function (options) {
                    $.ajax({
                        type: "GET",

                        url: "../ProductRequestGrid/GetInvlouedEmployees",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify({ key: "value" }),
                        success: function (data) {
                            options.success(data);
                        }
                    });
                }
            }
        });

        function dateTimeEditor(container, options) {
            $('<input data-text-field="' + options.field + '" data-value-field="' + options.field + '" data-bind="value:' + options.field + '" data-format="' + options.format + '"/>')
            .appendTo(container)
            .kendoDateTimePicker({});
        }
        $("#MessageGrid").kendoGrid({
            dataSource: dataSource,
            autoSync:false,
            scrollable: true,
            height: "250px",
            toolbar: [{ name: "create", text: "Create  Company Message" }, "excel"], //, "save", "cancel"],
            excel: {
                fileName: "CompanyMessagesExport.xlsx"
            },
            pageable: true,
            height: 300,
            columns: [
                  { field: "logInOwner", title: "Created User", filterable: true, width: "10em", editable: true },
                     {
                         field: "createdDate", title: "Created Date", filterable: true, width: "10em", format: "{0:MM/dd/yyyy HH:mm tt}"

                     },
    {
        field: "followUpdate", title: "Follow UpDate", filterable: false, format: "{0:MM/dd/yyyy HH:mm tt}",
        editor: dateTimeEditor, width: "8em",
        filterable: {
            ui: "datetimepicker"
        }
    },

     {
         field: "communicationDate", title: "Changed Date", filterable: false, format: "{0:MM/dd/yyyy HH:mm tt}",
         editor: dateTimeEditor, width: "8em",
         filterable: {
             ui: "datetimepicker"
         }
     },


             { field: "AllContacts", title: "AllContacts", filterable: false, editor: allcontactsDropDownEditor, width: "15em" },
             { field: "CompanyContacts", title: "Company Contact*", filterable: false, editor: companycontactnameDropDownEditor },
              { field: "companyoffice", title: "Office *", editor: officeDropDownEditor, width: "8em" },
              { field: "product", title: "Products *", editor: productDropDownEditor, filterable: false, width: "8em" },
              { field: "commVia", title: "Contacted Via *", editor: contactedviaDropDownEditor, width: "8em" },
           { field: "CommEmployee", title: "Assigned Employee", editor: invlouedEmployeeDropDownEditor, filterable: false, width: "10em" },
           { field: "phone", title: "Phone", width: "8em" },

           { field: "emailTo", title: "Email ", filterable: false, width: "8em" },
               { field: "inOrOut", title: "Incoming Or Outgoing ", editor: incomingOrOutgoingDropDownEditor, width: "8em" },
           { field: "statusName", title: "Status *", editor: statusDropDownEditor, filterable: false, width: "8em" },
          { field: "subject", title: "Subject", width: "8em" },


                             {
                                 title: "File Upload", width: "20em",
                                 //template: "<input type='file' name='files' id='files',data-role='upload', multiple='multiple', autocomplete='off'/>",
                                 template: "<input type='button' value='Upload File' onclick='ShowMessageFileUpload(#=id#)' />"
                                 //editor: generateButton
                             },
     {
         title: "UploadedFiles", width: "20em",
         template: "<input type='button' value='Show Upload File' onclick='showMessageUploadFiles(#=id#)' />"
     },

            {
                field: "FeedbackNote",
                title: "FeedbackNote",
                width: "200px",
                encoded: false
            },
            {
                field: "notes", title: "Notes", width: "200px", editor: function (container, options) {
                    $('<textarea data-bind="value: ' + options.field + '" cols="20" rows="10"></textarea>').appendTo(container);
                }
            },
          {
              title: "&nbsp;",
              width: "15em",
              //command: ["edit", "destroy"]
              command: [

                  "edit",
                  {
                      name: "Delete",


                      click: function (e) {
                          debugger;
                          var tr = $(e.target).closest("tr"); //get the row for deletion
                          var dataItem = this.dataItem(tr); //get the row data so it can be referred later


                          deleteTopicConfirmation(e, this);

                          return false;
                      }
                  }
              ]
          }
            ],
            filterable: {
                extra: false,
                operators: {
                    string: {
                        eq: "Is equal to",
                        neq: "Is not equal to",
                        contains: "Contains"
                    }
                }
            },

            editable: "popup",

            sortable: {
                mode: "single",
                allowUnsort: false
            },
            selectable: true,

            cancel: function () {
                gridInEditMode = false;
            },
            edit: function (e) {
                debugger;
                //e.container.find("input:first").hide();
                editedUID = e.model.uid;
                allContactIdsVar = e.model.AllContactIds;
                companyContactIdsVar = e.model.CompanyContactIds; //CompanyContactIds;
                assignedEmployeeIdVar = e.model.CommEmployeeIds;
                $('<a href="../AddProduct/ProductHistory"><img id="theImg" src="https://cdn0.iconfinder.com/data/icons/16x16-free-toolbar-icons/16/13.png" /></a>').insertAfter($("#ProductValue").parent());
                setVisibilityOfFollowup(e.model.statusName);
                e.container.find(".k-edit-label:nth-child(31)").hide();
                e.container.find(".k-edit-field:nth-child(32)").hide();
                e.container.find(".k-edit-label:nth-child(33)").hide();
                e.container.find(".k-edit-field:nth-child(34)").hide();
            }
        });


        $("#MessageGrid").kendoTooltip({
            filter: "td:nth-child(14)", //this filter selects the second column's cells
            position: "left",
            content: function (e) {
                var target = e.target;
                return $(target).text();

            }
        }).data("kendoTooltip");


        function productDropDownEditor(container, options) {

            $('<input  required="required" name="product" id="ProductValue" data-text-field="product" data-value-field="id"  data-bind="value:productID"/>').appendTo(container).kendoDropDownList({
                autoBind: true,
                dataValueField: "id",
                dataTextField: "product",
                dataSource: productdatasource
            });
            $('<span class="k-invalid-msg" data-for="product"></span>').appendTo(container);
        }
        function statusDropDownEditor(container, options) {

            $('<input required="required" name="status" id="StatusValue" data-text-field="statusName" data-value-field="status"  data-bind="value:statusID"/>').appendTo(container).kendoDropDownList({
                autoBind: true,
                dataValueField: "status",
                dataTextField: "statusName",
                dataSource: statusdatasource,
                change: function (e) {
                    setVisibilityOfFollowup(e.sender.text());
                },

            });
            $('<span class="k-invalid-msg" data-for="status"></span>').appendTo(container);
        }

        function setVisibilityOfFollowup(selectedValue) {
            debugger;
            if (selectedValue == "Follow Up") {
                $('div').find("[data-container-for=followUpdate]").prev().show();
                $('div').find("[data-container-for=followUpdate]").show();
            }
            else {
                $('div').find("[data-container-for=followUpdate]").prev().hide();
                $('div').find("[data-container-for=followUpdate]").hide();
            }
        }
        function contactedviaDropDownEditor(container, options) {

            $('<input   required="required" name="contactedVia" id="ContactedViaValue" data-text-field="commVia" data-value-field="id"  data-bind="value:communicationTypeID"/>').appendTo(container).kendoDropDownList({
                autoBind: true,
                dataValueField: "id",
                dataTextField: "commVia",
                dataSource: contactedviadatasource

            });
            $('<span class="k-invalid-msg" data-for="contactedVia"></span>').appendTo(container);

        }
        function officeDropDownEditor(container, options) {

            $('<input   required="required" name="office" id="officeId" data-text-field="companyoffice" data-value-field="officeId"  data-bind="value:officeId"/>').appendTo(container).kendoDropDownList({
                autoBind: true,
                dataValueField: "officeId",
                dataTextField: "companyoffice",
                dataSource: officedatasource
            });
            $('<span class="k-invalid-msg" data-for="office"></span>').appendTo(container);

        }
        function companycontactnameDropDownEditor(container, options) {

            $('<input id="officeId"  data-bind="value:CompanyContactIds" />').appendTo(container).kendoDropDownList({
                autoBind: false,
                dataValueField: "contactId",
                dataTextField: "name",
                dataSource: companycontactsdatasource,
                template: "<input type='checkbox' id='chk_CompCont_#=data.contactId #' onclick = 'UpdateIdinIsCompCont(this);' value='#=data.contactId #' name='chk_CompCont' />" + " " + "${ data.name }",
                close: function (e) {
                    if (IsCompContChecked == true) {
                        IsCompContChecked = false;
                        e.preventDefault();
                    }
                    else {
                        var allVals1 = [];
                        $("input[id*='chk_CompCont']:checked").each(function () {
                            allVals1.push($(this).val());
                        });

                        var gridList = $("#MessageGrid").data("kendoGrid").dataSource.data();
                        for (var i = 0; i < gridList.length; i++) {
                            if (gridList[i].uid == editedUID) {
                                gridList[i].CompanyContactIds = allVals1.join(",");
                                break;
                            }
                        }
                        e.sender.text(allVals1.length + " item(s) selected");
                    }
                },
                change: function (e) {
                    e.sender.value(null);
                },

                dataBound: function (e) {
                    var count = 0;
                    if (companyContactIdsVar) {
                        companyContactIdsVar = "," + companyContactIdsVar + ",";
                        $("input[id*='chk_CompCont']").each(function () {
                            if (companyContactIdsVar.indexOf("," + $(this).val() + ",") != -1) {
                                $(this).attr('checked', 'checked');
                                count++;
                            }
                        });
                        companyContactIdsVar = null;
                        e.sender.text(count + " item(s) selected");
                    }
                },




            });
            $('<span class="k-invalid-msg" data-for="companycontactname"></span>').appendTo(container);
        }
        function incomingOrOutgoingDropDownEditor(container, options) {
            $('<input id="InOrOutValue" data-text-field="dataText" data-value-field="dataText" data-bind="value:' + options.field + '" />').appendTo(container).kendoDropDownList({
                autoBind: false,
                dataSource: { data: [{ dataText: "In", dataValue: "1", selected: true }, { dataText: "Out", dataValue: "2" }] }

            });
        }

        function allcontactsDropDownEditor(container, options) {

            $('<input id="officeId"   data-bind="value:AllContactIds" />').appendTo(container).kendoDropDownList({
                autoBind: false,
                dataValueField: "id",
                dataTextField: "contactname",
                dataSource: allcontactsdatasource,
                template: "<input type='checkbox' id='chk_AllCont_#=data.id #' onclick='UpdateIdinIsAllCont(this);' value='#=data.id #' name='chk_AllCont' />" + " " + "${ data.contactname }",
                close: function (e) {
                    if (IsAllContChecked == true) {
                        IsAllContChecked = false;
                        e.preventDefault();
                    }
                    else {
                        var allVals2 = [];
                        $("input[id*='chk_AllCont']:checked").each(function () {
                            allVals2.push($(this).val());
                        });

                        var gridList = $("#MessageGrid").data("kendoGrid").dataSource.data();
                        for (var i = 0; i < gridList.length; i++) {
                            if (gridList[i].uid == editedUID) {
                                gridList[i].AllContactIds = allVals2.join(",");
                                break;
                            }
                        }

                        e.sender.text(allVals2.length + " item(s) selected");
                    }
                },
                change: function (e) {
                    e.sender.value(null);
                },
                dataBound: function (e) {
                    var count = 0;
                    if (allContactIdsVar) {
                        allContactIdsVar = "," + allContactIdsVar + ",";
                        $("input[id*='chk_AllCont']").each(function () {
                            if (allContactIdsVar.indexOf("," + $(this).val() + ",") != -1) {
                                $(this).attr('checked', 'checked');
                                count++;
                            }
                        });
                        allContactIdsVar = null;
                        e.sender.text(count + " item(s) selected");
                    }
                },
            });

        }

        function invlouedEmployeeDropDownEditor(container, options) {
            $('<input   id="invlouedEmployeeId"  data-bind="value:CommEmployeeIds" />').appendTo(container).kendoDropDownList({
                autoBind: false,
                dataValueField: "id",
                dataTextField: "InvoluedEname",
                dataSource: involuedEmployees,
                template: "<input type='checkbox' id='chk_AssEmp_#=data.id #' onclick='UpdateIdinIsAssEmp(this);' value='#=data.id #' name='chk_AssEmp' />" + " " + "${ data.InvoluedEname }",
                close: function (e) {
                    if (IsAssEmpChecked == true) {
                        IsAssEmpChecked = false;
                        e.preventDefault();
                    }
                    else {
                        var allVals = [];
                        $("input[id*='chk_AssEmp']:checked").each(function () {
                            allVals.push($(this).val());
                        });

                        var gridList = $("#MessageGrid").data("kendoGrid").dataSource.data();
                        for (var i = 0; i < gridList.length; i++) {
                            if (gridList[i].uid == editedUID) {
                                gridList[i].CommEmployeeIds = allVals.join(",");
                                break;
                            }
                        }

                        e.sender.text(allVals.length + " item(s) selected");
                    }
                },
                change: function (e) {
                    e.sender.value(null);
                },
                dataBound: function (e) {

                    var count = 0;
                    if (assignedEmployeeIdVar) {
                        assignedEmployeeIdVar = "," + assignedEmployeeIdVar + ",";
                        $("input[id*='chk_AssEmp']").each(function () {

                            if (assignedEmployeeIdVar.indexOf("," + $(this).val() + ",") != -1) {

                                $(this).attr('checked', 'checked');
                                count++;
                            }
                        });
                        assignedEmployeeIdVar = null;
                        e.sender.text(count + " item(s) selected");
                    }
                },
            });

        }

        function deleteTopicConfirmation(e, widget) {
            var grid = $('#MessageGrid').data("kendoGrid");
          //   $('#MessageGrid').data("kendoGrid").datasource.data([]);
            deleteConfirmation(e, widget, grid);
        }

        function deleteConfirmation(e, widget, grid) {

            var currentRow = $(e.target).closest("tr"); //get the row for deletion

            var currentRowData = widget.dataItem(currentRow); //get the row data so it can be  referred later

            var kendoWindow = $("<div />").kendoWindow({
                title: "Confirmation",
                resizable: true,
                modal: true,
                width: "400px",
                deactivate: function () {
                    $('.k-window, .k-overlay').remove();
                }
            });

            kendoWindow.data("kendoWindow")

                .content($("#delete-confirmation").html())

                .center().open();

            kendoWindow

                .find(".delete-confirm,.delete-cancel")
                .click(function () {
                    if ($(this).hasClass("delete-confirm")) {

                        grid.dataSource.remove(currentRowData);

                        grid.dataSource.sync();

                    }

                    $(this).closest("[data-role=window]").kendoWindow("close");

                });

        }
        dataSource.bind("requestEnd", showSuccessMessage);
        function showSuccessMessage(e) {
            if (e.type === "update" || e.type === "create") {
                gridInEditMode = false;
                e.sender.read();
            }
        }
        $(".close").click(function () {
            $(this).parent().removeClass('in');
        });
    }

    function ShowMessageFileUpload(id) {
        HideAllUplods();
        $("#MessageUpload").show();

        $("#hdnMessage").val(id);
    }
</script>

@* ...
    Show Project report

*@

<script type="text/javascript">
    function showReport(productRequestId) {
        HideAllUplods();
        //var dataSource = new kendo.data.DataSource({
        //    transport: {
        //        read: function (options) {
        $.ajax({
            type: "POST",
            url: "../ProductRequestGrid/generatePdf",
            contentType: "application/json; charset=utf-8",
            dataType: 'json',
            data: JSON.stringify({ productRequestId: productRequestId }),

            success: function (data) {
                $("#ireport").attr('src', data);
                $("#ireport").show();
                console.log(data);
                debugger;
            },

            error: function (request, status, error) {

                alert(request.responseText);
            }
        });
        // },

        //  }
        //  });
    }
</script>

@* ...
    Show Invoice PDF

*@


<script type="text/javascript">
    function showInvoicePDF(invoiceId) {
        HideAllUplods();
        $.ajax({
            type: "POST",
            url: "../Invoice/generateInvoicePdf",
            contentType: "application/json; charset=utf-8",
            dataType: 'json',
            data: JSON.stringify({ invoiceId: invoiceId }),

            success: function (data) {
                $("#iinvoicereport").attr('src', data);
                $("#iinvoicereport").show();
                console.log(data);
                debugger;
            },

            error: function (request, status, error) {
                debugger;

                alert(request.responseText);
            }
        });

    }

</script>

@* ...
    Show SendEmail

*@

<script type="text/javascript">
    function sendEmail(productRequestId) {

        HideAllUplods();
        $.ajax({
            type: "POST",
            url: "../ProductRequestGrid/generatePdf",
            contentType: "application/json; charset=utf-8",
            dataType: 'json',
            data: JSON.stringify({ productRequestId: productRequestId }),

            success: function (data) {
                $("#ireport").attr('src', data);
                $("#ireport").show();
                console.log(data);
                debugger;
            },

            error: function (request, status, error) {

                alert(request.responseText);
            }
        });
        // },

        //  }
        //  });
    }


    function GetContactsToSendReport(productRequestid, CompanyId) {
        $.ajax({
            type: "POST",
            url: "../ProductRequestGrid/GetContactsViewToSendReport",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify({ "productRequestId": productRequestid, "CompanyId": CompanyId }),
            success: function (data) {
                debugger;
                window.scrollTo(0, 0);
                $("#idEmployeeList").html('')
                $('#idEmployeeList').show();
                $("#idEmployeeList").html(data)
            }
        });
    }

    function CloseSendReport() {
        $('#idEmployeeList').hide();
    }

    function SendReport() {
        var productRequestid = $("#hdnProductID").val();
        var CompanyId = $("#hdnCompanyId").val();
        var SelectedMail = [];
        $.each($("input[class='chkChild']:checked"), function () {
            SelectedMail.push($(this).val());
        });
        //alert(SelectedMail.join("| "));
        if (SelectedMail.join("|") != null) {
            $.ajax({
                type: "POST",
                url: "../ProductRequestGrid/SendReportBySelectedMail",
                contentType: "application/json; charset=utf-8",
                data: JSON.stringify({ "productRequestId": productRequestid, "CompanyId": CompanyId, "SelectedMail": SelectedMail.join("|") }),
                success: function (data) {
                    alert(data);
                    CloseSendReport()
                }
            });
        }
        else {
            alert("Please select atleast one Person");
        }
    }
</script>


@* ...
    Show SendInvoiceEmail

*@
<script type="text/javascript">
    function sendInvoiceEmail(invoiceId) {

        HideAllUplods();
        $.ajax({
            type: "POST",
            url: "../Invoice/generateInvoicePdf",
            contentType: "application/json; charset=utf-8",
            dataType: 'json',
            data: JSON.stringify({ invoiceId: invoiceId }),

            success: function (data) {
                $("#ireport").attr('src', data);
                $("#ireport").show();
                console.log(data);
                debugger;
            },

            error: function (request, status, error) {

                alert(request.responseText);
            }
        });
        // },

        //  }
        //  });
    }


    function GetInvoiceContactsToSendReport(invoiceId, CompanyId) {
        $.ajax({
            type: "POST",
            url: "../Invoice/GetInvoiceContactsViewToSendReport",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify({ "invoiceId": invoiceId, "CompanyId": CompanyId }),
            success: function (data) {
                debugger;
                window.scrollTo(0, 0);
                $("#idInvoiceEmployeeList").html('')
                $('#idInvoiceEmployeeList').show();
                $("#idInvoiceEmployeeList").html(data)
            }
        });
    }

    function CloseInvoicePDFReport() {
        $('#idInvoiceEmployeeList').hide();
    }

    function showInvoiceSendReport(invoiceId, e, CompanyId) {
        $.ajax({
            type: "POST",
            url: "../Invoice/SendInvoiceReportBySelectedMail",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify({ "invoiceId": invoiceId, "CompanyId": CompanyId }),
            success: function (data) {
                alert(data);
            }
        });
    }
</script>

@* ...
    Show Invoice for Projects

*@
<script type="text/javascript">
    var IsInvoiceCompContChecked = false, invoicecompanyContactIdsVar = null;

    var editedUsID = "";

    function UpdateInvoiceIdinIsCompCont(e) {
        IsInvoiceCompContChecked = true;
    }
    function showInvoice(companyId, e) {
        HideAllUplods();
        $('#addcompanyGrid tr.k-state-selected').removeClass('k-state-selected');
        var row = $(e).closest("tr");
        row.addClass("k-state-selected");
        var gridInEditMode = false;
        $("#InvoiceGrid").show();
        $('#SalesLeadGrid').hide();
        $("#MessageGrid").hide();
        $('#companyofficegrid').hide();
        $('#SubTaskGrid').hide();
        $('#ServiceContractGrid').hide();
        $('#CompanyContactGrid').hide();
        $('#ProductRequestGrid').hide();
        $('#CompanyHistoryGrid').hide();

        $('#TaskGrid').hide();

        $("#InvoiceGrid").empty();
        var InvoiceGridDatasource = new kendo.data.DataSource({
            transport: {
                read: function (options) {
                    $.ajax({
                        type: "POST",
                        url: "/Invoice/GetInvoice",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        cache: false,
                        data: JSON.stringify({ id: companyId }),
                        success: function (data) {
                            debugger;
                            options.success(data);
                        }
                    });
                },
                create: function (options) {
                    var InvoiceVM = new Object();
                    InvoiceVM.id = options.data.id;
                    InvoiceVM.companyId = options.data.companyId;
                    InvoiceVM.companyId = companyId;
                    InvoiceVM.invoiceDate = options.data.invoiceDate;
                    if (options.data.productRequestId)
                        InvoiceVM.productRequestId = options.data.productRequestId.id;

                    InvoiceVM.period = options.data.period;
                    InvoiceVM.term = options.data.term;

                    InvoiceVM.notes = options.data.notes;
                    InvoiceVM.InvcompanyContactIds = options.data.InvcompanyContactIds;


                    $.ajax({
                        type: "POST",
                        url: "/Invoice/CreateInvoice",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify(InvoiceVM),
                        success: function (data) {
                            if (data.Message) {
                                alert(data.Message);
                            }
                            options.success(data);
                        },
                        error: function (request, status, error) {

                            alert(request.responseText);
                        }
                    });
                },

                update: function (options) {
                    var InvoiceVM = new Object();
                    InvoiceVM.id = options.data.id;
                    InvoiceVM.companyId = options.data.companyId;
                    InvoiceVM.companyId = companyId;

                    InvoiceVM.productRequestId = options.data.productRequestId;
                    InvoiceVM.invoiceDate = options.data.invoiceDate;

                    InvoiceVM.period = options.data.period;
                    InvoiceVM.term = options.data.term;

                    InvoiceVM.notes = options.data.notes;
                    InvoiceVM.InvcompanyContactIds = options.data.InvcompanyContactIds;
                    $.ajax({
                        type: "POST",
                        url: "/Invoice/UpdateInvoice",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify(InvoiceVM),
                        success: function (data) {
                            if (data.Message) {
                                alert(data.Message);
                            }
                            options.success(data);
                        }
                    });
                },

                destroy: function (options) {

                    $.ajax({
                        type: "POST",
                        url: "../Invoice/DeleteInvoice",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify({ id: options.data.id }),

                        success: function (data) {

                            options.success(data);
                        }
                    });
                },
                parameterMap: function (options) {
                    return kendo.stringify(options); // kendo.stringify serializes to JSON string
                }

            },

            pageSize: 5,
            schema: {
                model: {
                    id: "id",
                    fields: {
                        id: {
                            editable: false, nullable: true,
                            type: "int"
                        },
                        invoiceDate: {
                            type: "date",
                            nullable: true,
                            value: "",
                            defaultOption: null,
                            validation: { required: true }
                        },
                        description: {
                            type: "string"
                        },

                        empName: {
                            type: "string"
                        },

                        productName: {
                            type: "string",
                            validation: { required: true }
                        },
                        compName: {
                            type: "string",
                            // validation: { required: true }
                        },
                        clientContName: {
                            type: "string"
                        },
                        companyId: {
                            type: "int"
                        },
                        InvcompanyContacts: {
                            type: "string"
                        },

                        notes:
                            {
                                type: "string"
                            },

                        term:
                            {
                                type: "string",
                                validation: { required: true }
                            },
                        name:
                        {
                            type: "string"
                        },
                        productRequestId:
                            {
                                type: "int"
                            },

                        error: function (a) {
                            debugger;
                            $('#InvoiceGrid').data("kendoGrid").cancelChanges();
                        },

                    }
                }
            }

        });

        var companyDatasource = new kendo.data.DataSource({
            transport: {
                read: {
                    url: "/Invoice/GetAllCompanies/",
                    type: "POST",
                    contentType: "application/json",
                    cache: false,

                    dataType: "json"
                }
            }
        });
        var projectDatasource = new kendo.data.DataSource({

            transport: {

                read: function (options) {
                    $.ajax({
                        url: "/Invoice/GetAllProductsRequest/",
                        type: "POST",
                        contentType: "application/json",
                        cache: false,
                        data: JSON.stringify({ id: companyId }),
                        dataType: 'json',
                        cache: false,
                        success: function (data) {
                            debugger;
                            options.success(data);
                        }
                    });
                },
            }
        });
        var invoicecompanycontactsdatasource = new kendo.data.DataSource({
            transport: {
                read: function (options) {
                    $.ajax({
                        type: "POST",

                        url: "../CommunicationMessageGrid/GetAllCompanyContacts",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify({ id: companyId }),
                        success: function (data) {
                            options.success(data);
                        }
                    });
                }
            }
        });

        function dateTimeEditor(container, options) {
            $('<input data-text-field="' + options.field + '" data-value-field="' + options.field + '" data-bind="value:' + options.field + '" data-format="' + options.format + '"/>')
            .appendTo(container)
            .kendoDateTimePicker({});
        }
        $("#InvoiceGrid").kendoGrid({
            dataSource: InvoiceGridDatasource,
            scrollable: true,
            height: "250px",
            toolbar: [{ name: "create", text: "Add a Ivoice" }, "excel"], //, "save", "cancel"],
            excel: {
                fileName: "InvoiceExport.xlsx"
            },
            pageable: true,
            height: 300,

            columns: [

        { title: "items", filterable: false, width: "8em", template: "<a onclick=\"showInvoiceItems('#=id #',this);\"style=\"cursor: pointer;\"> View</a>" },
            { title: "PDF", filterable: false, width: "6em", template: "<a onclick=\"showInvoicePDF('#=id #',this);\"style=\"cursor: pointer;\"> View</a>" },
              { title: "SEND", filterable: false, width: "6em", template: "<a onclick=\"showInvoiceSendReport('#=id #',this, '" + companyId + "');\"style=\"cursor: pointer;\"> View</a>" },

             { field: "InvcompanyContacts", title: "Company Contact *", filterable: false, editor: invoicecompanycontactDropDownEditor },

           {
               field: "invoiceDate", title: "Date*", width: "10em", filterable: false, format: "{0:MM/dd/yyyy HH:mm tt}",
               editor: dateTimeEditor,
               filterable: {
                   ui: "datetimepicker"
               }
           },

            { field: "productName", title: "Product Name *", editor: projectDropDownEditor, filterable: true, width: "8em" },
             { field: "term", title: "Term *", filterable: true, editor: termDropdownEditor, width: "8em" },
               {
                   field: "notes", title: "Notes", filterable: true, width: "200px", editor: function (container, options) {
                       $('<textarea data-bind="value: ' + options.field + '" cols="20" rows="10"></textarea>').appendTo(container);
                   }
               },

          {
              title: "&nbsp;",
              width: "25em",
              //command: ["edit", "destroy"]
              command: [

                  "edit",
                  {
                      name: "Delete",


                      click: function (e) {

                          var tr = $(e.target).closest("tr"); //get the row for deletion
                          var dataItem = this.dataItem(tr); //get the row data so it can be referred later
                          //see what is coming in dataItem
                          //if (dataItem > 0) {
                          //    $("#delValidation").addClass('in')
                          //}
                          //else {

                          deleteTopicConfirmation(e, this);
                          ////}
                          return false;
                      }
                  }
              ]
          }
            ],
            filterable: {
                extra: false,
                operators: {
                    string: {
                        eq: "Is equal to",
                        neq: "Is not equal to",
                        contains: "Contains"
                    }
                }
            },

            editable: "popup",
            sortable: {
                mode: "single",
                allowUnsort: false
            },
            selectable: true,

            cancel: function () {
                gridInEditMode = false;
            },
            edit: function (e) {
                debugger;
                editedUsID = e.model.uid;
                invoicecompanyContactIdsVar = e.model.InvcompanyContactIds;
                e.container.find(".k-edit-label:nth-child(1)").hide();
                e.container.find(".k-edit-field:nth-child(1)").hide();

                e.container.find(".k-edit-label:nth-child(2)").hide();
                e.container.find(".k-edit-field:nth-child(2)").hide();
                e.container.find(".k-edit-label:nth-child(3)").hide();
                e.container.find(".k-edit-field:nth-child(3)").hide();
                e.container.find(".k-edit-label:nth-child(4)").hide();
                e.container.find(".k-edit-field:nth-child(4)").hide();
                e.container.find(".k-edit-label:nth-child(5)").hide();
                e.container.find(".k-edit-field:nth-child(5)").hide();
                e.container.find(".k-edit-field:nth-child(6)").hide();
            }
        });
        $("#InvoiceGrid").kendoTooltip({
            filter: "td:nth-child(8)", //this filter selects the second column's cells
            position: "left",
            content: function (e) {
                var target = e.target;
                return $(target).text();

            }
        }).data("kendoTooltip");



        function invoicecompanycontactDropDownEditor(container, options) {
            $('<input id="invoiceid"  data-bind="value:InvcompanyContactIds" />').appendTo(container).kendoDropDownList({
                autoBind: false,
                dataValueField: "ctId",
                dataTextField: "name",
                dataSource: invoicecompanycontactsdatasource,
                template: "<input type='checkbox' id='chk_InvcCompCont_#=data.ctId #' onclick = 'UpdateInvoiceIdinIsCompCont(this);' value='#=data.ctId #' name='chk_InvcCompCont_' />" + " " + "${ data.name }",
                close: function (e) {
                    if (IsInvoiceCompContChecked == true) {
                        IsInvoiceCompContChecked = false;
                        e.preventDefault();
                    }
                    else {
                        var allVals1 = [];
                        $("input[id*='chk_InvcCompCont']:checked").each(function () {
                            allVals1.push($(this).val());
                        });

                        var gridList = $("#InvoiceGrid").data("kendoGrid").dataSource.data();
                        for (var i = 0; i < gridList.length; i++) {
                            if (gridList[i].uid == editedUsID) {
                                gridList[i].InvcompanyContactIds = allVals1.join(",");
                                break;
                            }
                        }
                        e.sender.text(allVals1.length + " item(s) selected");
                    }
                },
                change: function (e) {
                    e.sender.value(null);
                },

                dataBound: function (e) {
                    var count = 0;
                    debugger;
                    if (invoicecompanyContactIdsVar) {
                        invoicecompanyContactIdsVar = "," + invoicecompanyContactIdsVar + ",";
                        $("input[id*='chk_InvcCompCont']").each(function () {
                            if (invoicecompanyContactIdsVar.indexOf("," + $(this).val() + ",") != -1) {
                                $(this).attr('checked', 'checked');
                                count++;
                            }
                        });
                        invoicecompanyContactIdsVar = null;
                        e.sender.text(count + " item(s) selected");
                    }
                },
            });
        }


        InvoiceGridDatasource.bind("requestEnd", showSuccessMessage);


        function showSuccessMessage(e) {
            if (e.type === "update" || e.type === "create") {
                InvoiceGrid.gridInEditMode = false;
                $("#saveConfirm").addClass('in');
                e.sender.read();
            }
        }


        $(".close").click(function () {
            $(this).parent().removeClass('in');
        });
        function deleteTopicConfirmation(e, widget) {
            var grid = $('#InvoiceGrid').data("kendoGrid");
            deleteConfirmation(e, widget, grid);
        }

        function deleteConfirmation(e, widget, grid) {

            var currentRow = $(e.target).closest("tr"); //get the row for deletion

            var currentRowData = widget.dataItem(currentRow); //get the row data so it can be  referred later

            var kendoWindow = $("<div />").kendoWindow({

                title: "Confirmation",
                resizable: true,
                modal: true,
                width: "400px",
                deactivate: function () {
                    $('.k-window, .k-overlay').remove();
                }

            });

            kendoWindow.data("kendoWindow")

                .content($("#delete-confirmation").html())

                .center().open();

            kendoWindow

                .find(".delete-confirm,.delete-cancel")
                .click(function () {
                    if ($(this).hasClass("delete-confirm")) {

                        grid.dataSource.remove(currentRowData);

                        grid.dataSource.sync();

                    }

                    $(this).closest("[data-role=window]").kendoWindow("close");

                });

        }

        function projectDropDownEditor(container, options) {

            $('<input required="required" name="project" id="ProductValue" data-text-field="name" data-value-field="id"  data-bind="value:productRequestId"/>').appendTo(container).kendoDropDownList({
                autoBind: true,
                dataValueField: "id",

                optionLabel: "Select project",
                dataTextField: "name",
                dataSource: projectDatasource
            });
            $('<span class="k-invalid-msg" data-for="project"></span>').appendTo(container);
        }

        function companyDropDownEditor(container, options) {

            $('<input required="required" name="company" id="cotValue" data-text-field="compName" data-value-field="id"  data-bind="value:companyId"/>').appendTo(container).kendoDropDownList({
                autoBind: true,
                dataValueField: "id",
                dataTextField: "compName",
                optionLabel: "Select Company ",
                dataSource: companyDatasource
            });
            $('<span class="k-invalid-msg" data-for="company"></span>').appendTo(container);
        }

        function termDropdownEditor(container, options) {
            $('<input  required="required" name="term"  id="termId" data-text-field="dataText" data-value-field="dataText"  data-bind="value:' + options.field + '"/>').appendTo(container).kendoDropDownList({
                autoBind: true,
                dataSource: {
                    data: [{ dataText: "Once", dataValue: "0" },
                        { dataText: "Weekly", dataValue: "7" },
                        { dataText: "Bi-Weekly", dataValue: "15" },
                        { dataText: "Monthly", dataValue: "30" },
                     { dataText: "Quaterly", dataValue: "120" },
                        { dataText: "Six Months", dataValue: "180" },
                        { dataText: "Yearly", dataValue: "360" }]
                },
                optionLabel: "Please select term",

            });
            $('<span class="k-invalid-msg" data-for="term"></span>').appendTo(container);
        }

    }

</script>
@* ...
    Show SubInvoiceItems for Projects

*@

<script>
    function showInvoiceItems(invoiceId, e) {
        HideAllUplods();
        var gridInEditMode = false;
        $('#InvoiceGrid tr.k-state-selected').removeClass('k-state-selected');
        var row = $(e).closest("tr");
        row.addClass("k-state-selected");
        $('#InvoiceItemsGrid').show();
        $("#MessageGrid").hide();
        $('#companyofficegrid').hide();
        $('#SubTaskGrid').hide();
        $('#ServiceContractGrid').hide();
        $('#CompanyContactGrid').hide();
        $('#ProductRequestGrid').hide();
        $('#CompanyHistoryGrid').hide();

        $('#TaskGrid').hide();
        $('#InvoiceItemsGrid').empty();
        var dataSource2 = new kendo.data.DataSource({
            transport: {
                read: function (options) {
                    $.ajax({
                        type: "POST",
                        url: "../InvoiceItems/GetInvoiceItems",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        cache: false,
                        data: JSON.stringify({ id: invoiceId }),
                        success: function (data) {

                            options.success(data);
                        },

                        error: function (request, status, error) {
                            alert(request.responseText);
                        }
                    });
                },

                create: function (options) {
                    debugger;
                    var InvoiceItemsVM = new Object();
                    InvoiceItemsVM.id = options.data.id;

                    InvoiceItemsVM.invoiceId = invoiceId;
                    InvoiceItemsVM.unitPrice = options.data.unitPrice;
                    InvoiceItemsVM.quantity = options.data.quantity;
                    InvoiceItemsVM.itemDescription = options.data.itemDescription;
                    InvoiceItemsVM.totalPrice = options.data.totalPrice;
                    $.ajax({
                        type: "POST",
                        url: "/InvoiceItems/CreateInvoiceItems",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify(InvoiceItemsVM),
                        success: function (data) {
                            if (data.Message) {
                                alert(data.Message);
                            }
                            options.success(data);
                        },
                        error: function (request, status, error) {
                            alert(request.responseText);
                        }
                    });
                },
                update: function (options) {
                    var InvoiceItemsVM = new Object();
                    InvoiceItemsVM.id = options.data.id;

                    InvoiceItemsVM.invoiceId = invoiceId;
                    InvoiceItemsVM.unitPrice = options.data.unitPrice;
                    InvoiceItemsVM.quantity = options.data.quantity;
                    InvoiceItemsVM.itemDescription = options.data.itemDescription;
                    InvoiceItemsVM.totalPrice = options.data.totalPrice;
                    $.ajax({
                        type: "POST",
                        url: "/InvoiceItems/UpdateInvoiceItems",
                        dataType: 'json',
                        data: JSON.stringify(InvoiceItemsVM),
                        contentType: "application/JSON",
                        success: function (data) {
                            if (data.Message) {
                                alert(data.Message);
                            }
                            options.success(data);
                        }
                    });
                },

                destroy: function (options) {
                    $.ajax({
                        type: "POST",
                        url: "../InvoiceItems/DeleteInvoiceItems",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify({ id: options.data.id }),

                        success: function (data) {

                            options.success(data);
                        }
                    });
                },
                parameterMap: function (options) {
                    return kendo.stringify(options); // kendo.stringify serializes to JSON string
                }
            },
            schema: {
                model: {
                    id: "id",
                    fields: {
                        id: {
                            editable: false, nullable: true,
                            type: "int"
                        },
                        invoiceId:
                            {
                                type: "int"
                            },

                        unitPrice:
                            {
                                type: "int",
                                validation: { required: true }
                            },

                        quantity: {
                            type: "int",
                            validation: { required: true }
                        },
                        itemDescription: {
                            type: "string"
                        },
                        totalPrice:
                            {
                                type: "decimal",
                                Visible: false

                            },

                        error: function (a) {
                            $('#productRequestGrid').data("kendoGrid").cancelChanges();
                        },
                    }
                }
            },
            aggregate: [
       { field: "totalPrice", aggregate: "sum" }
            ],

        });

        function dateTimeEditor(container, options) {
            $('<input data-text-field="' + options.field + '" data-value-field="' + options.field + '" data-bind="value:' + options.field + '" data-format="' + options.format + '"/>')
            .appendTo(container)
            .kendoDateTimePicker({});
        }

        $("#InvoiceItemsGrid").kendoGrid({
            dataSource: dataSource2,
            scrollable: true,
            height: "300px",
            toolbar: [{ name: "create", text: "Create InvoiceItems" }, "excel"], //, "save", "cancel"],
            excel: {
                allPages: true,
                fileName: "InvoiceItemsExport.xlsx"
            },
            pageable: true,
            scrollable: true,
            height: 250,
            columns: [
                     { field: "unitPrice", title: "Unit Price *", width: "9em" },
                       { field: "quantity", title: "Quantity *", width: "10em" },

                 { field: "totalPrice", title: "TotalPrice", width: "10em", footerTemplate: "Total Price: #= sum # " },

                 { field: "itemDescription", title: "Item Description", width: "10em" },

          {
              title: "&nbsp;",
              width: "10em",

              command: [

                  "edit",
                  {
                      name: "Delete",


                      click: function (e) {

                          var tr = $(e.target).closest("tr"); //get the row for deletion
                          var dataItem = this.dataItem(tr); //get the row data so it can be referred later
                          //see what is coming in dataItem
                          //if (dataItem.QuestionAnswers.length > 0) {
                          //    $("#delValidation").addClass('in')
                          //}
                          //else {

                          deleteTopicConfirmation(e, this);
                          //   }
                          return false;
                      }
                  }
              ]
          }
            ],
            filterable: {
                extra: false,
                operators: {
                    string: {
                        eq: "Is equal to",
                        neq: "Is not equal to",
                        contains: "Contains"
                    }
                }
            },
            editable: "popup",
            sortable: {
                mode: "single",
                allowUnsort: false
            },
            selectable: true,
            edit: function (e) {
                debugger;
                e.container.find("label[for=totalPrice]").parent("div .k-edit-label").hide();
                e.container.find("label[for=totalPrice]").parent().next("div .k-edit-field").hide();

                gridInEditMode = true;
            },
            excelExport: function (e) {
                for (var i = 0; i < e.workbook.sheets[0].columns.length; i++) {
                    e.workbook.sheets[0].columns[i].autoWidth = true;
                }
            },
            cancel: function () {
                gridInEditMode = false;
            },

        });
        function deleteTopicConfirmation(e, widget) {
            var grid = $('#InvoiceItemsGrid').data("kendoGrid");
            deleteConfirmation(e, widget, grid);
        }

        function deleteConfirmation(e, widget, grid) {

            var currentRow = $(e.target).closest("tr"); //get the row for deletion

            var currentRowData = widget.dataItem(currentRow); //get the row data so it can be  referred later

            var kendoWindow = $("<div />").kendoWindow({

                title: "Confirmation",
                resizable: true,
                modal: true,
                width: "400px",
                deactivate: function () {
                    $('.k-window, .k-overlay').remove();
                }
            });

            kendoWindow.data("kendoWindow")

                .content($("#delete-confirmation").html())

                .center().open();

            kendoWindow

                .find(".delete-confirm,.delete-cancel")
                .click(function () {
                    if ($(this).hasClass("delete-confirm")) {

                        grid.dataSource.remove(currentRowData);

                        grid.dataSource.sync();

                    }

                    $(this).closest("[data-role=window]").kendoWindow("close");

                });

        }
        dataSource2.bind("requestEnd", showSuccessMessage);
        function showSuccessMessage(e) {
            if (e.type === "update" || e.type === "create") {
                gridInEditMode = false;
                $("#saveConfirm").addClass('in');
                e.sender.read();
            }
        }
        $(".close").click(function () {
            $(this).parent().removeClass('in');
        });
    }
</script>


<style>
    .AutoCompleteHeader {
        background: #e80c4d;
        font-weight: bolder;
        font-size: 18px;
        color: white;
    }

    .dropdown-header {
        border-width: 0 0 2px 0;
        text-transform: uppercase;
    }

        .dropdown-header > span {
            display: inline-block;
            padding: 10px;
        }

            .dropdown-header > span:first-child {
                width: 50px;
            }

    #customers-list .k-item {
        line-height: 1em;
        min-width: 300px;
    }

    /* Material Theme padding adjustment*/

    .k-material #customers-list .k-item,
    .k-material #customers-list .k-item.k-state-hover,
    .k-materialblack #customers-list .k-item,
    .k-materialblack #customers-list .k-item.k-state-hover {
        padding-left: 5px;
        border-left: 0;
    }

    #customers-list .k-item > span {
        -webkit-box-sizing: border-box;
        -moz-box-sizing: border-box;
        box-sizing: border-box;
        display: inline-block;
        vertical-align: top;
        margin: 20px 10px 10px 5px;
    }

        #customers-list .k-item > span:first-child {
            -moz-box-shadow: inset 0 0 30px rgba(0,0,0,.3);
            -webkit-box-shadow: inset 0 0 30px rgba(0,0,0,.3);
            box-shadow: inset 0 0 30px rgba(0,0,0,.3);
            margin: 10px;
            width: 50px;
            height: 50px;
            border-radius: 50%;
            background-size: 100%;
            background-repeat: no-repeat;
        }

    #customers-list h3 {
        font-size: 1.2em;
        font-weight: normal;
        margin: 0 0 1px 0;
        padding: 0;
    }

    #customers-list p {
        margin: 0;
        padding: 0;
        font-size: .8em;
    }
</style>


<script id="delete-confirmation" type="text/x-kendo-template">

    <p class="delete-message">“Are you sure you want to delete the records?”</p>

    <button class="delete-confirm k-button btn btn-default">Yes</button>

    <button class="delete-cancel  k-button btn btn-default">No</button>

</script>
<input type="hidden" id="hdnUser" name="name" value=@User.Identity.Name />
<script type="text/javascript">
    function error_handler(e) {
        if (e.errors) {
            var message = "Errors:\n";
            $.each(e.errors, function (key, value) {
                if ('errors' in value) {
                    $.each(value.errors, function () {
                        message += this + "\n";
                    });
                }
            });
            alert(message);
        }
    }
</script>

<script type="text/javascript" src="~/Scripts/CallCenter/AddCompanyGrid.js"></script>
<script type="text/javascript" src="~/Scripts/CallCenter/ScratchPadAutoComplete.js"></script>
@* ...
    Generate Project and Invoice report using Iframe

*@
<iframe id="ireport" height="500px" style="display: none;" width="1200px"></iframe>
<iframe id="iinvoicereport" height="500px" style="display: none;" width="1200px"></iframe>

